JWT role Based Authorization with Spring Security

Viewed 3725

I would like to give access to /hello URL to users which has a role 'ADMIN' I have a security configuration like this. From "/authenticate" URL I am getting the jwt token.

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/authenticate").permitAll()
            //.antMatchers("/hello").hasRole("ADMIN")
            .anyRequest().authenticated().
            and().
            exceptionHandling().and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

I have tried to add @PreAuthorize annotation in my Controller, but it's not working all users have an access to that url.

    @GetMapping("/hello")
    @PreAuthorize("hasRole('ADMIN')")
    public String test(){
        return "Hello";
    }
1 Answers

After removing @PreAuthorize annotation from the controller and changing the security configuration like this it solved my problem.
@Darren Thanks a lot for your comment it resolved my issue.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/authenticate").permitAll()
        .antMatchers("/hello").hasAuthority("ADMIN")
        .anyRequest().authenticated().
        and().
        exceptionHandling().and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, 
        UsernamePasswordAuthenticationFilter.class);
}
Related