org.springframework.security.oauth2.common.exceptions.InvalidTokenException Java Examples
The following examples show how to use
org.springframework.security.oauth2.common.exceptions.InvalidTokenException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OAuth2JwtAccessTokenConverter.java From tutorials with MIT License | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #2
Source File: OAuth2JwtAccessTokenConverter.java From cubeai with Apache License 2.0 | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #3
Source File: SsoUserExtractor.java From cola with MIT License | 6 votes |
@Override public Object extractPrincipal(Map<String, Object> map) { Object authentication = map.get("userAuthentication"); if (authentication == null) { throw new InvalidTokenException("userAuthentication is empty"); } Object principal = ((Map<String, Object>) authentication).get("principal"); AuthenticatedUser user = new AuthenticatedUser(); if (principal == null) { throw new InvalidTokenException("principal is empty"); } try { BeanUtils.populate(user, (Map<String, Object>) principal); } catch (Exception e) { throw new InvalidTokenException("populate user error: " + e.getMessage()); } return user; }
Example #4
Source File: RefreshTokenFilter.java From cubeai with Apache License 2.0 | 6 votes |
/** * Refresh the access and refresh tokens if they are about to expire. * * @param httpServletRequest the servlet request holding the current cookies. If no refresh cookie is present, * then we are out of luck. * @param httpServletResponse the servlet response that gets the new set-cookie headers, if they had to be * refreshed. * @return a new request to use downstream that contains the new cookies, if they had to be refreshed. * @throws InvalidTokenException if the tokens could not be refreshed. */ public HttpServletRequest refreshTokensIfExpiring(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { HttpServletRequest newHttpServletRequest = httpServletRequest; //get access token from cookie Cookie accessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(httpServletRequest); if (mustRefreshToken(accessTokenCookie)) { //we either have no access token, or it is expired, or it is about to expire //get the refresh token cookie and, if present, request new tokens Cookie refreshCookie = OAuth2CookieHelper.getRefreshTokenCookie(httpServletRequest); if (refreshCookie != null) { try { newHttpServletRequest = authenticationService.refreshToken(httpServletRequest, httpServletResponse, refreshCookie); } catch (HttpClientErrorException ex) { throw new UnauthorizedClientException("could not refresh OAuth2 token", ex); } } else if (accessTokenCookie != null) { log.warn("access token found, but no refresh token, stripping them all"); OAuth2AccessToken token = tokenStore.readAccessToken(accessTokenCookie.getValue()); if (token.isExpired()) { throw new InvalidTokenException("access token has expired, but there's no refresh token"); } } } return newHttpServletRequest; }
Example #5
Source File: OAuth2JwtAccessTokenConverter.java From cubeai with Apache License 2.0 | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #6
Source File: OAuth2JwtAccessTokenConverter.java From cubeai with Apache License 2.0 | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #7
Source File: CustomAuthenticationManager.java From microservices-platform with Apache License 2.0 | 6 votes |
@Override public Mono<Authentication> authenticate(Authentication authentication) { return Mono.justOrEmpty(authentication) .filter(a -> a instanceof BearerTokenAuthenticationToken) .cast(BearerTokenAuthenticationToken.class) .map(BearerTokenAuthenticationToken::getToken) .flatMap((accessTokenValue -> { OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); if (accessToken == null) { return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue)); } else if (accessToken.isExpired()) { tokenStore.removeAccessToken(accessToken); return Mono.error(new InvalidTokenException("Access token expired: " + accessTokenValue)); } OAuth2Authentication result = tokenStore.readAuthentication(accessToken); if (result == null) { return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue)); } return Mono.just(result); })) .cast(Authentication.class); }
Example #8
Source File: OAuth2JwtAccessTokenConverter.java From cubeai with Apache License 2.0 | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #9
Source File: RedisAuthenticationManager.java From open-cloud with MIT License | 6 votes |
@Override public Mono<Authentication> authenticate(Authentication authentication) { return Mono.justOrEmpty(authentication) .filter(a -> a instanceof BearerTokenAuthenticationToken) .cast(BearerTokenAuthenticationToken.class) .map(BearerTokenAuthenticationToken::getToken) .flatMap((token -> { OAuth2Authentication oAuth2Authentication = this.tokenStore.readAuthentication(token); if(oAuth2Authentication==null){ return Mono.error(new InvalidTokenException(ErrorCode.INVALID_TOKEN.getMessage())); }else{ return Mono.just(oAuth2Authentication); } })) .cast(Authentication.class); }
Example #10
Source File: OAuth2JwtAccessTokenConverter.java From cubeai with Apache License 2.0 | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #11
Source File: OAuth2JwtAccessTokenConverter.java From cubeai with Apache License 2.0 | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #12
Source File: OAuth2JwtAccessTokenConverter.java From cubeai with Apache License 2.0 | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #13
Source File: SAPOfflineTokenServicesCloud.java From cloud-security-xsuaa-integration with Apache License 2.0 | 6 votes |
private Token checkAndCreateToken(@Nonnull String accessToken) { try { switch (serviceConfiguration.getService()) { case XSUAA: return new XsuaaToken(accessToken).withScopeConverter(xsuaaScopeConverter); case IAS: return new SapIdToken(accessToken); default: // TODO support IAS throw new InvalidTokenException( "AccessToken of service " + serviceConfiguration.getService() + " is not supported."); } } catch (Exception e) { throw new InvalidTokenException(e.getMessage()); } }
Example #14
Source File: GlobalExceptionHandler.java From lion with Apache License 2.0 | 6 votes |
/** * 声明要捕获的异常 * * @param e 异常 */ @ExceptionHandler(Exception.class) public Result exceptionHandler(Exception e) { Result result; if (e instanceof LionException) { LionException lionException = (LionException) e; result = Result.failure(lionException.getCode(), lionException.getMessage()); } else if (e instanceof InvalidTokenException) { result = Result.failure(ResponseCode.UNAUTHORIZED, "无效的 Access Token"); } else if (e instanceof InvalidGrantException) { result = Result.failure(ResponseCode.UNAUTHORIZED, "无效的 Refresh Token"); } else if (e instanceof AccessDeniedException) { result = Result.failure(ResponseCode.FORBIDDEN, "权限不足无法访问"); } else { log.error("系统异常", e); result = Result.failure(e.getMessage()); } return result; }
Example #15
Source File: MyUserInfoTokenServices.java From springboot-security-wechat with Apache License 2.0 | 6 votes |
public OAuth2Authentication loadAuthentication(String accessToken, String ip) throws AuthenticationException, InvalidTokenException { Map<String, Object> map = this.getMap(this.userInfoEndpointUrl, accessToken); for (Map.Entry<String, Object> entry : map.entrySet()) { System.out.println("key == " + entry.getKey() + " value == " + entry.getValue()); } if(map.containsKey("error")) { if(this.logger.isDebugEnabled()) { this.logger.debug("userinfo returned error: " + map.get("error")); } throw new InvalidTokenException(accessToken); } else { return this.extractAuthentication(map, ip); } }
Example #16
Source File: CustomAuthorizationTokenServices.java From Auth-service with MIT License | 6 votes |
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException, InvalidTokenException { OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); if (accessToken == null) { throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } else if (accessToken.isExpired()) { tokenStore.removeAccessToken(accessToken); throw new InvalidTokenException("Access token expired: " + accessTokenValue); } OAuth2Authentication result = tokenStore.readAuthentication(accessToken); if (result == null) { // in case of race condition throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } if (clientDetailsService != null) { String clientId = result.getOAuth2Request().getClientId(); try { clientDetailsService.loadClientByClientId(clientId); } catch (ClientRegistrationException e) { throw new InvalidTokenException("Client not valid: " + clientId, e); } } return result; }
Example #17
Source File: CustomAuthorizationTokenServices.java From microservice-integration with MIT License | 6 votes |
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException, InvalidTokenException { OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); if (accessToken == null) { throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } else if (accessToken.isExpired()) { tokenStore.removeAccessToken(accessToken); throw new InvalidTokenException("Access token expired: " + accessTokenValue); } OAuth2Authentication result = tokenStore.readAuthentication(accessToken); if (result == null) { // in case of race condition throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } if (clientDetailsService != null) { String clientId = result.getOAuth2Request().getClientId(); try { clientDetailsService.loadClientByClientId(clientId); } catch (ClientRegistrationException e) { throw new InvalidTokenException("Client not valid: " + clientId, e); } } return result; }
Example #18
Source File: CustomRemoteTokenServices.java From microservice-integration with MIT License | 6 votes |
@Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add(tokenName, accessToken); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret)); ServiceInstance serviceInstance = loadBalancerClient.choose(SecurityConstants.AUTH_SERVICE); if (serviceInstance == null) { throw new RuntimeException("Failed to choose an auth instance."); } Map<String, Object> map = postForMap(serviceInstance.getUri().toString() + checkTokenEndpointUrl, formData, headers); if (map.containsKey("error")) { logger.debug("check_token returned error: " + map.get("error")); throw new InvalidTokenException(accessToken); } Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server"); return tokenConverter.extractAuthentication(map); }
Example #19
Source File: BearerNoneTokenInfoResourceServerTokenServices.java From fullstop with Apache License 2.0 | 6 votes |
@Override public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException, InvalidTokenException { if (!StringUtils.hasText(accessToken)) { throw new InvalidTokenException("AccessToken should not be 'null', 'empty' or 'whitespace'"); } if (NONE.equalsIgnoreCase(accessToken)) { throw new InvalidTokenException("AccessToken should not be 'None'"); } if (accessToken.length() < 30) { throw new InvalidTokenException("AccessToken should have a length of 30 at least "); } return super.loadAuthentication(accessToken); }
Example #20
Source File: FacebookTokenServices.java From geowave with Apache License 2.0 | 6 votes |
@Override public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException, InvalidTokenException { final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add(tokenName, accessToken); final HttpHeaders headers = new HttpHeaders(); String req = ""; try { req = checkTokenEndpointUrl + "?access_token=" + URLEncoder.encode(accessToken, "UTF-8"); } catch (final UnsupportedEncodingException e) { logger.error("Unsupported encoding", e); } final Map<String, Object> map = getForMap(req, formData, headers); if (map.containsKey("error")) { logger.debug("check_token returned error: " + map.get("error")); throw new InvalidTokenException(accessToken); } return tokenConverter.extractAuthentication(map); }
Example #21
Source File: OAuth2JwtAccessTokenConverter.java From tutorials with MIT License | 6 votes |
/** * Try to decode the token with the current public key. * If it fails, contact the OAuth2 server to get a new public key, then try again. * We might not have fetched it in the first place or it might have changed. * * @param token the JWT token to decode. * @return the resulting claims. * @throws InvalidTokenException if we cannot decode the token. */ @Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) { throw new InvalidTokenException("public key expired"); } return super.decode(token); } catch (InvalidTokenException ex) { if (tryCreateSignatureVerifier()) { return super.decode(token); } throw ex; } }
Example #22
Source File: RefreshTokenFilter.java From tutorials with MIT License | 6 votes |
/** * Refresh the access and refresh tokens if they are about to expire. * * @param httpServletRequest the servlet request holding the current cookies. If no refresh cookie is present, * then we are out of luck. * @param httpServletResponse the servlet response that gets the new set-cookie headers, if they had to be * refreshed. * @return a new request to use downstream that contains the new cookies, if they had to be refreshed. * @throws InvalidTokenException if the tokens could not be refreshed. */ public HttpServletRequest refreshTokensIfExpiring(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { HttpServletRequest newHttpServletRequest = httpServletRequest; //get access token from cookie Cookie accessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(httpServletRequest); if (mustRefreshToken(accessTokenCookie)) { //we either have no access token, or it is expired, or it is about to expire //get the refresh token cookie and, if present, request new tokens Cookie refreshCookie = OAuth2CookieHelper.getRefreshTokenCookie(httpServletRequest); if (refreshCookie != null) { try { newHttpServletRequest = authenticationService.refreshToken(httpServletRequest, httpServletResponse, refreshCookie); } catch (HttpClientErrorException ex) { throw new UnauthorizedClientException("could not refresh OAuth2 token", ex); } } else if (accessTokenCookie != null) { log.warn("access token found, but no refresh token, stripping them all"); OAuth2AccessToken token = tokenStore.readAccessToken(accessTokenCookie.getValue()); if (token.isExpired()) { throw new InvalidTokenException("access token has expired, but there's no refresh token"); } } } return newHttpServletRequest; }
Example #23
Source File: CustomAuthorizationTokenServices.java From Auth-service with MIT License | 5 votes |
public String getClientId(String tokenValue) { OAuth2Authentication authentication = tokenStore.readAuthentication(tokenValue); if (authentication == null) { throw new InvalidTokenException("Invalid access token: " + tokenValue); } OAuth2Request clientAuth = authentication.getOAuth2Request(); if (clientAuth == null) { throw new InvalidTokenException("Invalid access token (no client id): " + tokenValue); } return clientAuth.getClientId(); }
Example #24
Source File: JwtTokenParser.java From multiapps-controller with Apache License 2.0 | 5 votes |
private void decodeAndVerify(String tokenString) { try { JwtHelper.decodeAndVerify(tokenString, getSignatureVerifier(getCachedTokenKey())); } catch (InvalidSignatureException e) { throw new InvalidTokenException(e.getMessage(), e); } }
Example #25
Source File: CustomUserInfoTokenServices.java From DAFramework with MIT License | 5 votes |
@Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { Map<String, Object> map = getMap(userInfoEndpointUrl, accessToken); if (map.containsKey("error")) { logger.debug("userinfo returned error: " + map.get("error")); throw new InvalidTokenException(accessToken); } return extractAuthentication(map); }
Example #26
Source File: OAuth2AuthenticationServiceTest.java From tutorials with MIT License | 5 votes |
/** * If no refresh token is found and the access token has expired, then expect an exception. */ @Test public void testRefreshGrantNoRefreshToken() { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com"); Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE); request.setCookies(accessTokenCookie); MockHttpServletResponse response = new MockHttpServletResponse(); expectedException.expect(InvalidTokenException.class); refreshTokenFilter.refreshTokensIfExpiring(request, response); }
Example #27
Source File: CustomTokenServicesTest.java From multiapps-controller with Apache License 2.0 | 5 votes |
@Test public void testWithExpiredToken() { OAuth2AccessToken token = buildInvalidToken(); prepareTokenParserChain(token); assertThrows(InvalidTokenException.class, () -> customTokenServices.loadAuthentication(DUMMY_TOKEN_STRING)); verify(tokenStore).removeAccessToken(eq(token)); }
Example #28
Source File: CustomUserInfoTokenServices.java From microservice-skeleton with MIT License | 5 votes |
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { Map map = this.getMap(this.userInfoEndpointUrl, accessToken); if (map.containsKey("error")) { this.logger.debug("userinfo returned error: " + map.get("error")); throw new InvalidTokenException(accessToken); } else { return this.extractAuthentication(map); } }
Example #29
Source File: JwtTokenParser.java From multiapps-controller with Apache License 2.0 | 5 votes |
protected void verifyToken(String tokenString) { try { decodeAndVerify(tokenString); } catch (InvalidTokenException e) { refreshTokenKey(); decodeAndVerify(tokenString); } }
Example #30
Source File: CustomAuthorizationTokenServices.java From microservice-integration with MIT License | 5 votes |
public String getClientId(String tokenValue) { OAuth2Authentication authentication = tokenStore.readAuthentication(tokenValue); if (authentication == null) { throw new InvalidTokenException("Invalid access token: " + tokenValue); } OAuth2Request clientAuth = authentication.getOAuth2Request(); if (clientAuth == null) { throw new InvalidTokenException("Invalid access token (no client id): " + tokenValue); } return clientAuth.getClientId(); }