spring - 登录后如何为当前用户添加新角色
问题描述
我在我的项目中使用弹簧安全登录。这是我的代码:
@Configuration
@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier(value = "loginServiceImpl")
private UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login**", "/js/**", "/css/**")
.permitAll()
.antMatchers("/role**")
.access("hasRole('ADMIN') and hasRole('ROLE')")
....
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and().exceptionHandling().accessDeniedPage("/403");
}
}
和
@Service
public class LoginServiceImpl implements UserDetailsService {
@Autowired
UserDao loginDao;
@Override
public UserDetails loadUserByUsername(String username) {
try {
net.liyan.psc.main.entity.main.User user = loginDao.findByUserNameForLogin(username);
if (user == null) throw new UsernameNotFoundException("User not found.");
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : loginDao.getAllRoleByUser(user)) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getCode()));
}
}
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
true,
true,
true,
true,
grantedAuthorities);
} catch (UsernameNotFoundException ex) {
throw new UsernameNotFoundException("User not found.");
}
}
}
有用。我可以得到当前用户
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
用户登录成功后,可以向当前用户(userDetails)添加新角色。我可以获得 userDetails.getAuthorities() 但没有任何 setter 或 add 方法来添加新角色。
解决方案
您可以更改用户的角色。您应该有一个从 org.springframework.security.core.userdetails.User 扩展的 userDetails 的构造函数。首先获取原始对象,然后对其进行操作或创建一个新实例。
这可以帮助您:
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Collection<GrantedAuthority> collection = userDetails.getAuthorities();
collection.add(yourAuthorities);
UserDetails user = new UserDetails(userDetails.getUsername(), userDetails.getPassword(), collection);
final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
推荐阅读
- python - 使用 Python 进行测试的自动构建文件
- slack - 为什么我会从 Slack Incoming Webhook 获得完整的降价响应?
- sql - Postgres 发现价值的变化
- javascript - 使用 mapStateToProps 和 connect() 调度后 React 组件未重新渲染
- go - 从 cmd 输出写入文件
- javascript - 警告:componentWillReceiveProps 已重命名,不推荐使用。请更新以下组件:控件
- javascript - 如何在用户操作之前停止执行 javascript 函数?
- node.js - ElectronJS 必须使用 import 来加载 ES Module
- javascript - 在 go 函数中等待 js 异步函数(promise)
- highslide - 如何禁用 highslide.js 中的所有动画?