0

I'm allways having an error when testing service in postman for example if i test ModeratorAccess() it always generate 401 Bad Credentials. i think the problem in the configuration but i hope the jwt token part is good.

enter image description here

this is my configuration file :

@Configuration
@EnableAspectJAutoProxy

@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        // jsr250Enabled = true,
        prePostEnabled = true,
        proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests().antMatchers("/api/auth/**").permitAll()
            .antMatchers("/api/test/**").permitAll()
            .anyRequest().authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

and this is my controller:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class TestController {
    @GetMapping("/all")
    public String allAccess() {
        return "Public Content.";
    }
    
    @GetMapping("/user")
    @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
    public String userAccess() {
        return "User Content.";
    }

    @GetMapping("/mod")
    @PreAuthorize("hasRole('MODERATOR')")
    //@PreAuthorize("permitAll")
    public String moderatorAccess() {
        return "Moderator Board.";
    }

    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String adminAccess() {
        return "Admin Board.";
    }
}

I'm new to spring security.

mimozgh
  • 5
  • 3
  • This is not how you implement the handling of jwts in spring security. Spring security already has a fully customizable jwtfilter and writing your own is bad practice. Please read the jwtchapter in the docs how to build this correctly – Toerktumlare Jul 18 '22 at 21:54

1 Answers1

-1

there are a few points to be checked for 401 error

  1. Try removing @preAuthorise from your method moderatorAccess() as you have already said that here

    .antMatchers("/api/test/**").permitAll() .anyRequest().authenticated();

  2. check the token passed in your header and your jwtfilter class, if you are following any tutorial, usually we make wrong key , so the token in header should be like key: Authorization and value as Bearer 'your toke here' , plaster your filter code here for reference

3.You can remove the annotation @preauthorise and try this

antMatchers("/api/auth/seller/**").hasAuthority("ADMIN").
  1. Also when granting roles to the users, people make a mistake in role and Authority

    a role is just an authority with a special ROLE_ prefix. So in Spring security 3 @PreAuthorize("hasRole('ROLE_XYZ')") is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')") and in Spring security 4 @PreAuthorize("hasRole('XYZ')") is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')").

Read more here - Difference between Role and GrantedAuthority in Spring Security

  1. check the token generated is for the correct role, like in your database the user is the moderator role and you are creating jwt token with that user and hitting an API with admin access

  2. Check if there is an error in configuring by disabling spring security and check if the endpoint is working by removing the spring security

  3. you can also enable formLogin in the same method of WebSecurityConfigurerAdapter like .formLogin() and try to hit the API with your browser using standard login page provided by spring security

  4. Compare your code with this github repo having basic implementation of what you are trying to do https://github.com/koushikkothagal/spring-security-jwt

  • The github repo provided has a custom JWTFilter solution which is bad practice. Spring security comes with a built in fully customizable jwtfilter and its clear that the author hasnt even read the jwt chapter of the spring documentation. – Toerktumlare Jul 18 '22 at 21:51
  • I am aware of the custom jwtfilter but, I was trying to list out the options the author can try to fix his issue, He is new to spring world. – sarthak sethi Jul 19 '22 at 06:31
  • If he is new dont link and advice him to use bad practices – Toerktumlare Jul 19 '22 at 08:33
  • The first step should be helping someone, not yelling its a bad practice, you are doing it wrong, etc, this never helps, You know some stuff, help him out, instead of saying, he has not read properly and read the documentation, May be, has tried all which he can and asked the question. you never know what all he has gone through before posting the question – sarthak sethi Jul 19 '22 at 10:43
  • Asking on stack overflow should not be taken lightly. This not a forum, its a last resort after doing lots of research and reading documentation. Just because one is new is not an excause to not at least look at the official documentation. He has not included what he has tried in the question but one thing is for sure, neither of you both have even read the chapter on jwts in the spring docs before asking/answering – Toerktumlare Jul 19 '22 at 11:57
  • You should read this https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users – Toerktumlare Jul 19 '22 at 11:58