Search in sources :

Example 36 with AccessToken

use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.

the class OpenAMTokenStore method createAccessToken.

/**
     * {@inheritDoc}
     */
public AccessToken createAccessToken(String grantType, String accessTokenType, String authorizationCode, String resourceOwnerId, String clientId, String redirectUri, Set<String> scope, RefreshToken refreshToken, String nonce, String claims, OAuth2Request request) throws ServerException, NotFoundException {
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();
    String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    long expiryTime = 0;
    if (clientRegistration == null) {
        expiryTime = providerSettings.getAccessTokenLifetime() + System.currentTimeMillis();
    } else {
        expiryTime = clientRegistration.getAccessTokenLifeTime(providerSettings) + System.currentTimeMillis();
    }
    final AccessToken accessToken;
    if (refreshToken == null) {
        accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, null, OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
    } else {
        accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, refreshToken.getTokenId(), OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
    }
    try {
        tokenStore.create(accessToken);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_TOKEN", accessToken.toString() };
            auditLogger.logAccessMessage("CREATED_TOKEN", obs, null);
        }
    } catch (CoreTokenException e) {
        logger.error("Could not create token in CTS: " + e.getMessage());
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_TOKEN", accessToken.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_TOKEN", obs, null);
        }
        throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }
    request.setToken(AccessToken.class, accessToken);
    return accessToken;
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AccessToken(org.forgerock.oauth2.core.AccessToken) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 37 with AccessToken

use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.

the class OpenAMTokenStore method appendRequestedIdTokenClaims.

//See spec section 5.5. - add claims to id_token based on 'claims' parameter in the access token
private void appendRequestedIdTokenClaims(OAuth2Request request, OAuth2ProviderSettings providerSettings, OpenAMOpenIdConnectToken oidcToken) throws ServerException, NotFoundException, InvalidClientException {
    AccessToken accessToken = request.getToken(AccessToken.class);
    String claims;
    if (accessToken != null) {
        claims = (String) accessToken.toMap().get(OAuth2Constants.Custom.CLAIMS);
    } else {
        claims = request.getParameter(OAuth2Constants.Custom.CLAIMS);
    }
    if (claims != null) {
        try {
            JSONObject claimsObject = new JSONObject(claims);
            JSONObject idTokenClaimsRequest = claimsObject.getJSONObject(OAuth2Constants.JWTTokenParams.ID_TOKEN);
            Map<String, Object> userInfo = providerSettings.getUserInfo(accessToken, request).getValues();
            Iterator<String> it = idTokenClaimsRequest.keys();
            while (it.hasNext()) {
                String keyName = it.next();
                if (userInfo.containsKey(keyName)) {
                    oidcToken.put(keyName, userInfo.get(keyName));
                }
            }
        } catch (UnauthorizedClientException e) {
            throw failureFactory.getException(request, e.getMessage());
        } catch (JSONException e) {
        //if claims object not found, fall through
        }
    }
}
Also used : JSONObject(org.json.JSONObject) AccessToken(org.forgerock.oauth2.core.AccessToken) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject)

Example 38 with AccessToken

use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.

the class DeviceCodeGrantTypeHandlerTest method setup.

@BeforeMethod
public void setup() throws Exception {
    initMocks(this);
    OAuth2ProviderSettingsFactory providerSettingsFactory = mock(OAuth2ProviderSettingsFactory.class);
    when(providerSettingsFactory.get(request)).thenReturn(providerSettings);
    when(providerSettings.getDeviceCodePollInterval()).thenReturn(5);
    when(providerSettings.validateRequestedClaims(anyString())).thenAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return (String) invocation.getArguments()[0];
        }
    });
    OAuth2UrisFactory oAuth2UrisFactory = mock(OAuth2UrisFactory.class);
    when(oAuth2UrisFactory.get(request)).thenReturn(oAuth2Uris);
    ClientAuthenticator clientAuthenticator = mock(ClientAuthenticator.class);
    ClientRegistration clientRegistration = mock(ClientRegistration.class);
    when(clientAuthenticator.authenticate(eq(request), anyString())).thenReturn(clientRegistration);
    accessTokenGenerator = new GrantTypeAccessTokenGenerator(tokenStore);
    when(tokenStore.createAccessToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anySetOf(String.class), any(RefreshToken.class), anyString(), anyString(), any(OAuth2Request.class))).thenReturn(accessToken);
    when(tokenStore.createRefreshToken(anyString(), anyString(), anyString(), anyString(), anySetOf(String.class), any(OAuth2Request.class), anyString())).thenReturn(refreshToken);
    ClientAuthenticationFailureFactory failureFactory = mock(ClientAuthenticationFailureFactory.class);
    InvalidClientException expectedResult = mock(InvalidClientException.class);
    when(expectedResult.getError()).thenReturn("invalid_client");
    when(failureFactory.getException()).thenReturn(expectedResult);
    when(failureFactory.getException(anyString())).thenReturn(expectedResult);
    when(failureFactory.getException(any(OAuth2Request.class), anyString())).thenReturn(expectedResult);
    grantTypeHandler = new DeviceCodeGrantTypeHandler(providerSettingsFactory, clientAuthenticator, tokenStore, clientRegistrationStore, failureFactory, oAuth2UrisFactory, accessTokenGenerator);
}
Also used : ClientAuthenticationFailureFactory(org.forgerock.oauth2.core.exceptions.ClientAuthenticationFailureFactory) InvocationOnMock(org.mockito.invocation.InvocationOnMock) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 39 with AccessToken

use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.

the class AccessTokenProtectionFilter method beforeHandle.

@Override
protected int beforeHandle(Request request, Response response) {
    ChallengeResponse challengeResponse = request.getChallengeResponse();
    Status failure = null;
    if (challengeResponse == null) {
        failure = new Status(401, new InvalidTokenException());
    } else {
        String tokenId = challengeResponse.getRawValue();
        try {
            OAuth2Request oAuth2Request = requestFactory.create(request);
            AccessToken accessToken = tokenStore.readAccessToken(oAuth2Request, tokenId);
            if (accessToken == null || accessToken.isExpired()) {
                failure = new Status(401, new InvalidTokenException());
            } else if (requiredScope != null && !accessToken.getScope().contains(requiredScope)) {
                failure = new Status(403, new InsufficientScopeException(requiredScope));
            } else {
                oAuth2Request.setToken(AccessToken.class, accessToken);
            }
        } catch (ServerException e) {
            failure = new Status(500, e);
        } catch (NotFoundException e) {
            debug.message("Error loading token with id: " + tokenId, e);
            failure = new Status(404, e);
        } catch (InvalidGrantException e) {
            debug.message("Error loading token with id: " + tokenId, e);
            failure = new Status(401, new InvalidTokenException());
        }
    }
    if (failure != null) {
        response.setStatus(failure);
        return STOP;
    }
    return super.beforeHandle(request, response);
}
Also used : Status(org.restlet.data.Status) InvalidTokenException(org.forgerock.oauth2.core.exceptions.InvalidTokenException) InsufficientScopeException(org.forgerock.oauth2.core.exceptions.InsufficientScopeException) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AccessToken(org.forgerock.oauth2.core.AccessToken) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException) ChallengeResponse(org.restlet.data.ChallengeResponse)

Example 40 with AccessToken

use of org.forgerock.oauth2.core.AccessToken in project OpenAM by OpenRock.

the class OpenAMScopeValidator method evaluateScope.

/**
     * {@inheritDoc}
     */
public Map<String, Object> evaluateScope(AccessToken accessToken) {
    final Map<String, Object> map = new HashMap<String, Object>();
    final Set<String> scopes = accessToken.getScope();
    if (scopes.isEmpty()) {
        return map;
    }
    final String resourceOwner = accessToken.getResourceOwnerId();
    final String clientId = accessToken.getClientId();
    final String realm = accessToken.getRealm();
    AMIdentity id = null;
    try {
        if (clientId != null && CLIENT_CREDENTIALS.equals(accessToken.getGrantType())) {
            id = identityManager.getClientIdentity(clientId, realm);
        } else if (resourceOwner != null) {
            id = identityManager.getResourceOwnerIdentity(resourceOwner, realm);
        }
    } catch (Exception e) {
        logger.error("Unable to get user identity", e);
    }
    if (id != null) {
        for (String scope : scopes) {
            try {
                Set<String> attributes = id.getAttribute(scope);
                StringBuilder builder = new StringBuilder();
                if (CollectionUtils.isNotEmpty(attributes)) {
                    Iterator<String> iter = attributes.iterator();
                    while (iter.hasNext()) {
                        builder.append(iter.next());
                        if (iter.hasNext()) {
                            builder.append(MULTI_ATTRIBUTE_SEPARATOR);
                        }
                    }
                }
                map.put(scope, builder.toString());
            } catch (Exception e) {
                logger.error("Unable to get attribute", e);
            }
        }
    }
    return map;
}
Also used : AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) AMIdentity(com.sun.identity.idm.AMIdentity) JSONObject(org.json.JSONObject) ScriptObject(org.forgerock.openam.scripting.ScriptObject) JSONException(org.json.JSONException) ParseException(java.text.ParseException) ScriptException(javax.script.ScriptException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) SSOException(com.iplanet.sso.SSOException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) InvalidScopeException(org.forgerock.oauth2.core.exceptions.InvalidScopeException)

Aggregations

AccessToken (org.forgerock.oauth2.core.AccessToken)37 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)22 Test (org.testng.annotations.Test)17 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)14 JsonValue (org.forgerock.json.JsonValue)13 Request (org.restlet.Request)12 ChallengeResponse (org.restlet.data.ChallengeResponse)10 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)9 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)7 AccessTokenVerifier (org.forgerock.oauth2.core.AccessTokenVerifier)6 Response (org.restlet.Response)6 Map (java.util.Map)5 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)5 InvalidGrantException (org.forgerock.oauth2.core.exceptions.InvalidGrantException)5 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)5 BeforeMethod (org.testng.annotations.BeforeMethod)5 HashMap (java.util.HashMap)4 ResourceOwner (org.forgerock.oauth2.core.ResourceOwner)4 InvalidTokenException (org.forgerock.oauth2.core.exceptions.InvalidTokenException)4 JSONObject (org.json.JSONObject)4