org.springframework.security.oauth2.core.OAuth2AuthenticationException Java Examples

The following examples show how to use org.springframework.security.oauth2.core.OAuth2AuthenticationException. 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: CustomTokenResolver.java    From oauth2-resource with MIT License 6 votes vote down vote up
protected String resolveFromCookie(HttpServletRequest request) {

        String cookieToken = null;
        //根据请求数据,找到cookie数组
        Cookie[] cookies = request.getCookies();

        if (null != cookies && cookies.length > 0) {
            int foundTimes = 0;
            for (Cookie cookie : cookies) {
                if (null != cookie.getName() && "access_token".equalsIgnoreCase(cookie.getName().trim())) {
                    cookieToken = cookie.getValue().trim();
                    foundTimes++;
                }
            }
            if (foundTimes > 1) {
                BearerTokenError error = new BearerTokenError("invalid_request", HttpStatus.BAD_REQUEST, "Found multiple tokens in the request", "https://tools.ietf.org/html/rfc6750#section-3.1");
                throw new OAuth2AuthenticationException(error);
            }
        }
        return cookieToken;
    }
 
Example #2
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
    RequestEntity requestEntity = RequestEntity
        .post(URI.create(clientRegistration.getProviderDetails().getTokenUri()))
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .body(formParameters);

    try {
        ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
        return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to get access token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
 
Example #3
Source File: AuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) {

        MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
        formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue());
        formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue());
        formParameters.add(OAuth2ParameterNames.CLIENT_ID, currentClient.getClientRegistration().getClientId());
        RequestEntity requestEntity = RequestEntity
            .post(URI.create(currentClient.getClientRegistration().getProviderDetails().getTokenUri()))
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .body(formParameters);
        try {
            RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret());
            ResponseEntity<OAuthIdpTokenResponseDTO> responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class);
            return toOAuth2AccessTokenResponse(responseEntity.getBody());
        } catch (OAuth2AuthorizationException e) {
            log.error("Unable to refresh token", e);
            throw new OAuth2AuthenticationException(e.getError(), e);
        }
    }
 
Example #4
Source File: RoleAwareOAuth2UserService.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
  // Delegate to the default implementation for loading a user
  OidcUser oidcUser = delegate.loadUser(userRequest);

  // Fetch the authority information from the protected resource using idToken
  Collection<GrantedAuthority> mappedAuthorities =
      extractAuthorities(userRequest, extractOnlyOpendevstackRoles);
  mappedAuthorities.addAll(oidcUser.getAuthorities());

  // Create a copy of oidcUser but use the mappedAuthorities instead
  DefaultOidcUser oidcUserWithAuthorities =
      new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
  return oidcUserWithAuthorities;
}
 
Example #5
Source File: CustomTokenResolver.java    From oauth2-resource with MIT License 5 votes vote down vote up
private static String resolveFromAuthorizationHeader(HttpServletRequest request) {
    String authorization = request.getHeader("Authorization");
    if (StringUtils.hasText(authorization)) {
        Matcher matcher = AUTHORIZATION_PATTERN.matcher(authorization);
        if (!matcher.matches()) {
            BearerTokenError error = new BearerTokenError("invalid_token", HttpStatus.UNAUTHORIZED, "Bearer token is malformed", "https://tools.ietf.org/html/rfc6750#section-3.1");
            throw new OAuth2AuthenticationException(error);
        } else {
            return matcher.group("token");
        }
    } else {
        return null;
    }
}
 
Example #6
Source File: CustomTokenResolver.java    From oauth2-resource with MIT License 5 votes vote down vote up
private static String resolveFromRequestParameters(HttpServletRequest request) {
    String[] values = request.getParameterValues("access_token");
    if (values != null && values.length != 0) {
        if (values.length == 1) {
            return values[0];
        } else {
            BearerTokenError error = new BearerTokenError("invalid_request", HttpStatus.BAD_REQUEST, "Found multiple tokens in the request", "https://tools.ietf.org/html/rfc6750#section-3.1");
            throw new OAuth2AuthenticationException(error);
        }
    } else {
        return null;
    }
}
 
Example #7
Source File: OidcUserManagementAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
Set<GrantedAuthority> extract(final ClientRegistration clientRegistration, final String tokenValue) {
    try {
        // Token is already verified by spring security
        final JwtDecoder jwtDecoder = new NimbusJwtDecoderJwkSupport(
                clientRegistration.getProviderDetails().getJwkSetUri());
        final Jwt token = jwtDecoder.decode(tokenValue);

        return extract(clientRegistration.getClientId(), token.getClaims());
    } catch (final JwtException e) {
        throw new OAuth2AuthenticationException(INVALID_REQUEST, e);
    }
}
 
Example #8
Source File: OAuth2MappingUserService.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    OAuth2User auth = super.loadUser(userRequest);
    Map<String, Object> map = auth.getAttributes();

    UserData data = new UserData(map);

    Registration.User user = registration.getOrRegister(data.id(), data.email(), data.readableName());
    
    return user;
}