Why Refreshing access token gets unauthorized?

rupal3112

As access token expires, client sends GET request with /refresh endpoint,but it ended with 401-unauthorized.

I have configured this request in webConfig. so, it does not need authorization. I have passed access token in header of /refresh request.

Note: If I don't pass token in header of /refresh request, It worked fine.

JwtAuthenticationController.java:

@RestController
public class JwtAuthenticationController {

    @RequestMapping(value = "/refresh", method = RequestMethod.GET)
    public ResponseEntity<?> refreshAuthenticationToken(HttpServletRequest request) {

        final String token = request.getHeader("Authorization");

        final String username = jwtUtils.getUsernameFromToken(token);
        final UserDetails user =  userDetailsService.loadUserByUsername(username);

        if ((user.getUsername()).equals(username) && jwtUtils.isTokenExpired(token)) {
            final String refreshedToken = jwtUtils.refreshToken(token);
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
        } 
        else {
            return ResponseEntity.badRequest().body(null);
        }
    }
}

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()             
                .exceptionHandling()
               .antMatchers("/register","/refresh")
               .permitAll()                   
               .anyRequest().authenticated();                     

        httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
        httpSecurity.headers().cacheControl().disable();
    }
}

JwtAuthenticationFilter.java

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        String authToken = request.getHeader(AUTHORIZATION_HEADER);

        if (authToken != null && authToken.startsWith(BEARER_PREFIX)) {
            try {
                authToken = authToken.substring(BEARER_PREFIX_LENGTH);
                username = jwtUtils.getUsernameFromToken(authToken);
            }catch (IllegalArgumentException e) {
                System.out.println("Unable to get JWT Token");
            } catch (ExpiredJwtException e) {
                System.out.println("JWT Token has expired");
            }
        }
        else {
        logger.warn("JWT Token does not begin with Bearer String");
   }
}

JwtUtils.java

private Claims getClaimsFromToken(String token) {
     return Jwts.parser()
                .setSigningKey(secret)
                .requireIssuer(issuer)
                .parseClaimsJws(token)
                .getBody();
}

error log

I am unable to find out why this happen? What is the solution to get new access token using client sent refresh token.

zakaria amine

If I don't pass token in header of /refresh request, It worked fine.

This is probably because of the JwtAuthenticationFilter. I think you should exclude also the /refresh from the check, so:

   if (!request.getRequestURI().contains("/refresh") {
    if (authToken != null && authToken.startsWith(BEARER_PREFIX)) {
    //same logic
    }
   }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Spring OAuth2 refresh token to change after refreshing access token

Facebook: Refreshing long-lived access token automatically

Refreshing an OAuth access token for Microsoft Live API

Why isn't OAuth2 client refreshing expired access_token?

Client secret + refreshing the access token in spring oauth2

401 Unauthorized response for access_token in the developer sandbox

Refresh Token gets revoked with Access Token in Laravel Passport

Why changeResourceRecordSets gets not authorized to access this resource?

Automating access token refreshing via interceptors in axios

Why does Podio return an unauthorized response when I am submitting a valid access token?

OpenID Connect: Proper way of authenticating user - ID token or Access token? Refreshing ID tokens?

Refreshing an Access Token for Client Credentials Flow

Refreshing the access token from azure ad

Call Custom REST API When Refreshing Access Token

Accessing TeamCity using Authenticationn/Access Token gives error 401 Unauthorized

Authenticating / Refreshing Google API access token and avoiding a "file in use" exception?

How do I test refreshing my google access token using a refresh token

Circumstances of the "invalid_grant" error when refreshing an access token?

unauthorized_Client while refreshing google access token

Error refreshing the OAuth2 token, message: '{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." }'

Asana API Personal Access Token return 401 (Unauthorized)

Google OAuth 403 when refreshing access token

Issue while refreshing access token in angular 5

Web API refresh token not refreshing when access token is expired

Web API access token not refreshing after it's expired

401 unauthorized: Access token validation failure calling Sharepoint

Why does PyDrive stop refreshing the access token after a while?

Stop paypal access token from refreshing so frequently

Google OAuth, refreshing access token (grant type)