Java Code Examples for org.springframework.security.oauth2.common.exceptions.InvalidTokenException

The following examples show how to use org.springframework.security.oauth2.common.exceptions.InvalidTokenException. These examples are extracted from open source projects. 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
@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 2
Source Project: open-cloud   Source File: RedisAuthenticationManager.java    License: MIT License 6 votes vote down vote up
@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 3
Source Project: cola   Source File: SsoUserExtractor.java    License: MIT License 6 votes vote down vote up
@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 Project: cubeai   Source File: OAuth2JwtAccessTokenConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 5
Source Project: cubeai   Source File: OAuth2JwtAccessTokenConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: cubeai   Source File: OAuth2JwtAccessTokenConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: cubeai   Source File: RefreshTokenFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 8
Source Project: cubeai   Source File: OAuth2JwtAccessTokenConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: cubeai   Source File: OAuth2JwtAccessTokenConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 10
Source Project: cubeai   Source File: OAuth2JwtAccessTokenConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: cubeai   Source File: OAuth2JwtAccessTokenConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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
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 13
Source Project: lion   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 声明要捕获的异常
 *
 * @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 14
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 15
Source Project: Auth-service   Source File: CustomAuthorizationTokenServices.java    License: MIT License 6 votes vote down vote up
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 16
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
@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 18
@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 19
Source Project: geowave   Source File: FacebookTokenServices.java    License: Apache License 2.0 6 votes vote down vote up
@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 20
Source Project: tutorials   Source File: OAuth2JwtAccessTokenConverter.java    License: MIT License 6 votes vote down vote up
/**
 * 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 21
Source Project: tutorials   Source File: RefreshTokenFilter.java    License: MIT License 6 votes vote down vote up
/**
 * 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 22
Source Project: tutorials   Source File: OAuth2JwtAccessTokenConverter.java    License: MIT License 6 votes vote down vote up
/**
 * 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 23
@Override
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 24
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 25
Source Project: cubeai   Source File: OAuth2CookieHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the given claim from the given token.
 *
 * @param refreshToken the JWT token to examine.
 * @param claimName    name of the claim to get.
 * @param clazz        the Class we expect to find there.
 * @return the desired claim.
 * @throws InvalidTokenException if we cannot find the claim in the token or it is of wrong type.
 */
@SuppressWarnings("unchecked")
private <T> T getClaim(String refreshToken, String claimName, Class<T> clazz) {
    Jwt jwt = JwtHelper.decode(refreshToken);
    String claims = jwt.getClaims();
    Map<String, Object> claimsMap = jsonParser.parseMap(claims);
    Object claimValue = claimsMap.get(claimName);
    if (claimValue == null) {
        return null;
    }
    if (!clazz.isAssignableFrom(claimValue.getClass())) {
        throw new InvalidTokenException("claim is not of expected type: " + claimName);
    }
    return (T) claimValue;
}
 
Example 26
Source Project: cubeai   Source File: OAuth2AuthenticationServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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
@Override
public OAuth2Authentication loadAuthentication(@Nonnull String accessToken)
		throws AuthenticationException, InvalidTokenException {
	Token token = checkAndCreateToken(accessToken);

	ValidationResult validationResult = tokenValidator.validate(token);

	if (validationResult.isErroneous()) {
		throw new InvalidTokenException(validationResult.getErrorDescription());
	}
	SecurityContext.setToken(token);

	return getOAuth2Authentication(serviceConfiguration.getClientId(), getScopes(token));
}
 
Example 28
@Test
public void loadAuthentication_tokenValidationFailed_throwsException() {
	when(jwtValidatorBuilderMock.build()).thenCallRealMethod();
	cut.afterPropertiesSet();

	assertThatThrownBy(() -> cut.loadAuthentication(xsuaaToken)).isInstanceOf(InvalidTokenException.class);

	assertThat(SecurityContext.getToken()).isNull();
}
 
Example 29
@Test
public void createInstanceWithClientIdConfiguration_throwsException() {
	OAuth2ServiceConfiguration mockConfiguration = Mockito.mock(OAuth2ServiceConfiguration.class);
	when(mockConfiguration.getClientId()).thenReturn("clientId");

	cut = new SAPOfflineTokenServicesCloud(mockConfiguration);
	cut.afterPropertiesSet();
	assertThatThrownBy(() -> cut.loadAuthentication(xsuaaToken)).isInstanceOf(InvalidTokenException.class);
}
 
Example 30
Source Project: lion   Source File: CustomAuthenticationEntryPoint.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

    log.error(authException.getMessage());

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");

    Throwable cause = authException.getCause();
    if (cause instanceof InvalidTokenException) {
        response.getWriter().print(JsonUtil.jsonObj2Str(Result.failure(ResponseCode.UNAUTHORIZED, "无效的 Access Token")));
    } else if (cause instanceof InvalidGrantException) {
        response.getWriter().print(JsonUtil.jsonObj2Str(Result.failure(ResponseCode.UNAUTHORIZED, "无效的 Refresh Token")));
    } else if (cause instanceof AccessDeniedException) {
        response.getWriter().print(JsonUtil.jsonObj2Str(Result.failure(ResponseCode.FORBIDDEN, "权限不足无法访问")));
    } else {
        response.getWriter().print(JsonUtil.jsonObj2Str(Result.failure(ResponseCode.UNAUTHORIZED, "尚未认证无法访问")));
    }

    /*
    if (isAjaxRequest(request)) {
        response.sendError(HttpStatus.UNAUTHORIZED.value(), authException.getMessage());
    } else {
        response.sendRedirect("/login");
    }
    */

}