【发布时间】:2015-06-21 19:35:07
【问题描述】:
截至Spring Security doc: 34.1 @EnableWebMvcSecurity 状态,@EnableWebMvcSecurity 已替换为@EnableWebSecurity。
但是当我尝试通过@AuthenticationPrincipal 获取控制器中的UserDetails 时,我得到了一个空对象:用户名是""。我也试过@EnableWebMvcSecurity,但不幸的是UserDetails是null。
但我可以通过传统方式获得UserDetails,如下所示:
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
我的问题是,当我使用 @EnableWebSecurity 时,获取自定义 UserDetails (Account) 的正确方法是什么?
以下是相关源码:
控制器:
@RequestMapping(method = RequestMethod.POST)
@Secured("ROLE_USER")
public String postRoom(@Valid @ModelAttribute Room room, BindingResult result, Model model, @AuthenticationPrincipal Account principal) {
if (result.hasErrors()) {
return "room_form";
}
Account account = accountRepository.findByUsername(principal.getUsername());
room.setAccountId(account.getId());
room.setLastModified(new Date());
roomRepository.save(room);
return "room_list";
}
安全配置:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private SecurityProperties security;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll()
.and().formLogin().loginPage("/login").failureUrl("/login?error").permitAll()
.and().logout().permitAll()
.and().rememberMe()
.and().csrf().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(this.dataSource).passwordEncoder(new BCryptPasswordEncoder(8));
}
}
还有Account.java:
@Entity
@Table(name = "users")
public class Account implements Serializable {
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
private boolean enabled;
@Lob
private byte[] avatar;
// getter / setter ...
}
【问题讨论】:
-
或许也可以添加您的安全配置。
Account是用来通过UserDetailsService进行身份验证的对象吗?还可以尝试使用Principal对象而不是Account,看看是否有任何结果。 -
嗨,吉姆,我也有类似的问题。您是否找到了通过上下文获得
Principal而使用@AuthenticationPrincipal注释时却没有的原因? -
没有。请尝试传统方式。
标签: spring spring-mvc spring-security