简体   繁体   中英

JWT with Spring Boot and Mysql, getting an error "status": 401, "error": "Unauthorized", while giving an access roles

protected void configure(HttpSecurity http) throws Exception{ http.csrf().disable().cors().disable().authorizeRequests()
.antMatchers("/**","/user/**","/document/**","/appointment/**","/activity/**").hasAuthority(UserRole.ADMIN.name())      .antMatchers("/user/","/document/**","/appointment/**","/activity/**").hasAuthority(UserRole.ADMIN.name())      .antMatchers("/user/**","/activity/**","/appointment/","/document/","/appointment/**","/document/**").hasAuthority((UserRole.SUPPORTEXECUTIVE.name()))      .antMatchers("/user/**","/activity/**","/appointment/","/document/","/appointment/**").hasAuthority((UserRole.FIELDEXECUTIVE.name()))
.and().exceptionHandling().authenticationEntryPoint(invaildUserAuthEntryPoint).and().sessionManagement()        .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().addFilterBefore(securityFilter,UsernamePasswordAuthenticationFilter.class);
protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain) throws
  ServletException, IOException
  {  
      String token = request.getHeader("Authorization");      
      if(token != null) 
      { 
          String username = util.getUsername(token);  
          
          if(username != null && SecurityContextHolder.getContext().getAuthentication() == null)
          {   
              UserDetails usr = userDetailsService.loadUserByUsername(username);
              System.out.println(usr);
              boolean isValid = util.validateToken(token, usr.getUsername());
              
              if(isValid)
              {                   
                  UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username,usr.getPassword(),usr.getAuthorities());   
                  authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));   
                  SecurityContextHolder.getContext().setAuthentication(authToken);  
              }  
          }  
      } 
      filterChain.doFilter(request, response); 
  }
}
public ResponseEntity<UserResponse> loginUser(@RequestBody UserRequest request) throws Exception
    {  
        try
        {
              authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUserEmail(),request.getPassword()));      
              String token = utill.genrateToken(request.getUserEmail());    
              System.out.println("Token :" +token);
              return ResponseEntity.ok(new UserResponse(token));
        }
        catch (DisabledException e)
        {
             throw new Exception("USER_DISABLED", e);
        } 
        catch (BadCredentialsException e) 
        {
             throw new Exception("INVALID_CREDENTIALS", e);
         }
     
    }
    

When given the access for.antmatchers.permitALL() the token is generated and given access with generated token only, but after applying.hasAuthority(Role) we get unauthorized user error.

{
    "timestamp": "2022-12-13T11:51:52.606+00:00",
    "status": 401,
    "error": "Unauthorized",
}

Expecting Token generation with hasAuthority() and access the roles for particular user.

Generally, 401 occurs when you provide the wrong credentials.

if credentials are proper then it seems like you are missing the authority column in your users table, everything else looks fine. Maybe this link will help you JWT-based authorization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM