I have implemented spring security in my application. It is stateless-token based authentication and username/password based authentication.
I have configured user authentication, but the role-based authorisation is not working.
A user who has ROLE_USER
is able to access the controller method which has ROLE_ADMIN
.
Here is the configuration.
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Bean
AuthenticationProvider passwordBasedAuthenticationProvider() {
return new PasswordBasedAuthenticationProvider();
}
@Bean
AuthenticationProvider tokenBasedAuthenticationProvider(){
return new TokenBasedAuthenticationProvider();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/v1/public/**");
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
csrf().disable().
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().
authorizeRequests().
anyRequest().authenticated().
and().
anonymous().disable();
http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(passwordBasedAuthenticationProvider()).
authenticationProvider(tokenBasedAuthenticationProvider());
}
}
DOMAINS
@Entity
public class Role implements GrantedAuthority {
private long id;
private String authority;
}
public class User implements UserDetails{
private String username;
private String passwordHash;
private Role role;
}
@RestController
public class TesController {
@RequestMapping(value="/authController")
@Secured("ROLE_ADMIN")
String test(){ return "I am secure for ROLE_ADMIN"}
}
What is incorrect about this configuration?