Search in sources :

Example 21 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.

the class DefaultTokenServices method refreshAccessToken.

@Transactional(noRollbackFor = { InvalidTokenException.class, InvalidGrantException.class })
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
    if (!supportRefreshToken) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }
    OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
    if (refreshToken == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }
    OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
    if (this.authenticationManager != null && !authentication.isClientOnly()) {
        // The client has already been authenticated, but the user authentication might be old now, so give it a
        // chance to re-authenticate.
        Authentication user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities());
        user = authenticationManager.authenticate(user);
        Object details = authentication.getDetails();
        authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
        authentication.setDetails(details);
    }
    String clientId = authentication.getOAuth2Request().getClientId();
    if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
        throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
    }
    // clear out any access tokens already associated with the refresh
    // token.
    tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
    if (isExpired(refreshToken)) {
        tokenStore.removeRefreshToken(refreshToken);
        throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
    }
    authentication = createRefreshedAuthentication(authentication, tokenRequest);
    if (!reuseRefreshToken) {
        tokenStore.removeRefreshToken(refreshToken);
        refreshToken = createRefreshToken(authentication);
    }
    OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
    tokenStore.storeAccessToken(accessToken, authentication);
    if (!reuseRefreshToken) {
        tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
    }
    return accessToken;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 22 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.

the class ImplicitTokenGranter method getOAuth2Authentication.

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) {
    Authentication userAuth = SecurityContextHolder.getContext().getAuthentication();
    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InsufficientAuthenticationException("There is no currently logged in user");
    }
    Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest.");
    OAuth2Request requestForStorage = ((ImplicitTokenRequest) clientToken).getOAuth2Request();
    return new OAuth2Authentication(requestForStorage, userAuth);
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 23 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project spring-security-oauth by spring-projects.

the class ResourceOwnerPasswordTokenGranter method getOAuth2Authentication.

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
    String username = parameters.get("username");
    String password = parameters.get("password");
    // Protect from downstream leaks of password
    parameters.remove("password");
    Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
    ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
    try {
        userAuth = authenticationManager.authenticate(userAuth);
    } catch (AccountStatusException ase) {
        //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
        throw new InvalidGrantException(ase.getMessage());
    } catch (BadCredentialsException e) {
        // If the username/password are wrong the spec says we should send 400/invalid grant
        throw new InvalidGrantException(e.getMessage());
    }
    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InvalidGrantException("Could not authenticate user: " + username);
    }
    OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
    return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
Also used : AccountStatusException(org.springframework.security.authentication.AccountStatusException) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) LinkedHashMap(java.util.LinkedHashMap)

Example 24 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project ORCID-Source by ORCID.

the class OrcidRefreshTokenChecker method validateRequest.

public void validateRequest(String grantType, TokenRequest tokenRequest, Long requestTimeInMillis) {
    String authorization = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.AUTHORIZATION);
    String clientId = tokenRequest.getClientId();
    String scopes = tokenRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    Long expireIn = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.EXPIRES_IN) ? Long.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.EXPIRES_IN)) : 0L;
    String refreshToken = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.REFRESH_TOKEN);
    OrcidOauth2TokenDetail token = orcidOauth2TokenDetailDao.findByTokenValue(authorization);
    // Verify the token belongs to this client
    if (!clientId.equals(token.getClientDetailsId())) {
        throw new IllegalArgumentException("This token doesnt belong to the given client");
    }
    // Verify client is enabled
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    // Verify the token is not expired
    if (token.getTokenExpiration() != null) {
        if (token.getTokenExpiration().before(new Date())) {
            throw new InvalidTokenException("Access token expired: " + authorization);
        }
    }
    // Verify access token and refresh token are linked
    if (!refreshToken.equals(token.getRefreshTokenValue())) {
        throw new InvalidTokenException("Token and refresh token does not match");
    }
    // Verify the token is not disabled
    if (token.getTokenDisabled() != null && token.getTokenDisabled()) {
        throw new InvalidTokenException("Parent token is disabled");
    }
    // Verify scopes are not wider than the token scopes
    if (PojoUtil.isEmpty(scopes)) {
        scopes = token.getScope();
    } else {
        Set<ScopePathType> requiredScopes = ScopePathType.getScopesFromSpaceSeparatedString(scopes);
        Set<ScopePathType> simpleTokenScopes = ScopePathType.getScopesFromSpaceSeparatedString(token.getScope());
        // This collection contains all tokens that should be allowed given
        // the scopes that the parent token contains
        Set<ScopePathType> combinedTokenScopes = new HashSet<ScopePathType>();
        for (ScopePathType scope : simpleTokenScopes) {
            combinedTokenScopes.addAll(scope.combined());
        }
        // combinedTokenScopes
        for (ScopePathType scope : requiredScopes) {
            if (!combinedTokenScopes.contains(scope)) {
                throw new InvalidScopeException("The given scope '" + scope.value() + "' is not allowed for the parent token");
            }
        }
    }
    // Validate the expiration for the new token is no later than the parent
    // token expiration.
    long parentTokenExpiration = token.getTokenExpiration() == null ? System.currentTimeMillis() : token.getTokenExpiration().getTime();
    if (expireIn > parentTokenExpiration) {
        throw new IllegalArgumentException("Token expiration can't be after " + token.getTokenExpiration());
    }
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) ScopePathType(org.orcid.jaxb.model.message.ScopePathType) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) Date(java.util.Date) HashSet(java.util.HashSet)

Example 25 with TokenRequest

use of org.springframework.security.oauth2.provider.TokenRequest in project ORCID-Source by ORCID.

the class OrcidClientCredentialEndPointDelegatorImpl method generateToken.

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code, String redirectUri, String grantType, String refreshToken, String state, String authorization, boolean revokeOld, Long expiresIn) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();
    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }
    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao.find(code);
        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }
            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE) || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
            //This will pass through to the token generator as a request param.
            if (authorizationCodeEntity.getNonce() != null) {
                authorizationParameters.put(OrcidOauth2Constants.NONCE, authorizationCodeEntity.getNonce());
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    //If it is a refresh token request, set the needed authorization parameters
    if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
        authorizationParameters.put(OrcidOauth2Constants.AUTHORIZATION, authorization);
        authorizationParameters.put(OrcidOauth2Constants.REVOKE_OLD, String.valueOf(revokeOld));
        authorizationParameters.put(OrcidOauth2Constants.EXPIRES_IN, String.valueOf(expiresIn));
        authorizationParameters.put(OrcidOauth2Constants.REFRESH_TOKEN, String.valueOf(refreshToken));
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(authorizationParameters);
    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);
    //Need to change this to either the DefaultTokenType or start using a different token type.
    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object[] params = { grantType };
    if (token == null) {
        LOGGER.info("Unsupported grant type for OAuth2: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info("OAuth2 access token granted: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}, token={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri, token });
    return token;
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException)

Aggregations

TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)40 Test (org.junit.Test)38 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)34 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)33 Authentication (org.springframework.security.core.Authentication)25 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)21 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)13 HashMap (java.util.HashMap)11 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)11 ModelAndView (org.springframework.web.servlet.ModelAndView)10 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)9 TokenGranter (org.springframework.security.oauth2.provider.TokenGranter)9 RedirectView (org.springframework.web.servlet.view.RedirectView)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)8 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)7 DefaultUserApprovalHandler (org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler)7 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)6 Date (java.util.Date)5 HashSet (java.util.HashSet)5 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)5