Не удается получить аннотации @Secured Method Security, работающие в Spring Security
Я сделал много исследований, и для меня все выглядит правильно ... но я не могу заставить это работать! У кого-нибудь есть идеи?
Независимо от того, что я делаю, соответствующее сопоставление остается открытым для всех (анонимно или зарегистрировано, независимо от того, какую роль они имеют).
В идеале я хотел бы, чтобы ВСЕ запросы были открытыми, кроме тех, которые аннотированы @Secured () - очевидно, только пользователям с определенными ролями будет разрешен доступ к этим сопоставлениям.
Это возможно?
В качестве обходного пути я в настоящее время создал метод hasRole (String role), который проверяет роль вошедшего в систему пользователя и выдает NotAuthorizedException (выполненный на заказ), если метод возвращает значение false.
UserDetails
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> grantedAuthorities = null;
System.out.print("Account role... ");
System.out.println(account.getRole());
if (account.getRole().equals("USER")) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
grantedAuthorities = Arrays.asList(grantedAuthority);
}
if (account.getRole().equals("ADMIN")) {
GrantedAuthority grantedAuthorityUser = new SimpleGrantedAuthority("ROLE_USER");
GrantedAuthority grantedAuthorityAdmin = new SimpleGrantedAuthority("ROLE_ADMIN");
grantedAuthorities = Arrays.asList(grantedAuthorityUser, grantedAuthorityAdmin);
}
return grantedAuthorities;
}
SecurityConfig
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthFailure authFailure;
@Autowired
private AuthSuccess authSuccess;
@Autowired
private EntryPointUnauthorizedHandler unauthorizedHandler;
@Autowired
private UserDetailsServiceImpl userDetailsService;
/*@Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService);
}*/
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
@Override
public void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService);
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().csrfTokenRepository(csrfTokenRepository())
.and().exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and().formLogin().loginPage("/login").successHandler(authSuccess).failureHandler(authFailure)
//.and().authorizeRequests().antMatchers("/rest/**").authenticated()
//.and().authorizeRequests().antMatchers("/**").permitAll()
.and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);;
}
AccountController
@Secured("ROLE_USER")
@RequestMapping(method = RequestMethod.GET)
public List<Account> getAllAccounts(@RequestParam(value = "mail", required = false) String mail) {
Спасибо!