samedi 18 avril 2015

AuthenticationPrincipal is empty when using EnableWebSecurity

As of Spring Security doc: 34.1 @EnableWebMvcSecurity states, the @EnableWebMvcSecurity was replaced by @EnableWebSecurity.

But when I try to get the UserDetails in controller by the @AuthenticationPrincipal, I got a empty object - the username is "".

I also tried the @EnableWebMvcSecurity, but unfortunately, the UserDetails is null!

But I can get the UserDetails by the traditional way, like this:



SecurityContextHolder.getContext().getAuthentication().getPrincipal();


My question is, what the correct way to get my custom UserDetails (Account) when I use @EnableWebSecurity?


Below are the related source code:


Controller:



@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";
}


security configuration:



@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));
}
}


And the 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 ...
}

Aucun commentaire:

Enregistrer un commentaire