Search in sources :

Example 41 with Token

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

the class LegacyResponseTypeHandler method handle.

public Map.Entry<String, org.forgerock.oauth2.core.Token> handle(String tokenType, Set<String> scope, ResourceOwner resourceOwner, String clientId, String redirectUri, String nonce, OAuth2Request request, String codeChallenge, String codeChallengeMethod) throws NotFoundException {
    final Map<String, Object> data = new HashMap<String, Object>();
    data.put(TOKEN_TYPE, tokenType);
    data.put(SCOPE, scope);
    data.put(USERNAME, resourceOwner.getId());
    data.put(CLIENT_ID, clientId);
    data.put(REDIRECT_URI, redirectUri);
    data.put(OAuth2Constants.Custom.NONCE, nonce);
    data.put(REALM, realm);
    data.put(OAuth2Constants.Custom.CODE_CHALLENGE, codeChallenge);
    data.put(OAuth2Constants.Custom.CODE_CHALLENGE_METHOD, codeChallengeMethod);
    final HttpServletRequest req = ServletUtils.getRequest(request.<Request>getRequest());
    data.put(OAuth2Constants.Custom.SSO_TOKEN_ID, cookieExtractor.extract(req, ssoCookieName));
    final CoreToken token = responseType.createToken(request.getToken(AccessToken.class), data);
    return new AbstractMap.SimpleEntry<String, org.forgerock.oauth2.core.Token>(responseType.URIParamValue(), new LegacyToken(token));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HashMap(java.util.HashMap) AccessToken(org.forgerock.oauth2.core.AccessToken)

Example 42 with Token

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

the class ScopeImpl method getUserInfo.

/**
     * {@inheritDoc}
     */
public UserInfoClaims getUserInfo(CoreToken token) {
    Set<String> scopes = token.getScope();
    Map<String, Object> response = new HashMap<String, Object>();
    AMIdentity id = null;
    try {
        id = identityManager.getResourceOwnerIdentity(token.getUserID(), token.getRealm());
    } catch (UnauthorizedClientException e) {
        throw OAuthProblemException.OAuthError.UNAUTHORIZED_CLIENT.handle(null, e.getMessage());
    }
    //add the subject identifier to the response
    response.put("sub", token.getUserID());
    for (String scope : scopes) {
        if (OPENID_SCOPE.equals(scope)) {
            continue;
        }
        //get the attribute associated with the scope
        Object attributes = scopeToUserUserProfileAttributes.get(scope);
        if (attributes == null) {
            logger.error("ScopeImpl.getUserInfo()::Invalid Scope in token scope=" + scope);
        } else if (attributes instanceof String) {
            Set<String> attr = null;
            //if the attribute is a string get the attribute
            try {
                attr = id.getAttribute((String) attributes);
            } catch (IdRepoException e) {
                logger.warning("ScopeImpl.getUserInfo(): Unable to retrieve attribute= " + attributes, e);
            } catch (SSOException e) {
                logger.warning("ScopeImpl.getUserInfo(): Unable to retrieve attribute= " + attributes, e);
            }
            //add a single object to the response.
            if (attr != null && attr.size() == 1) {
                response.put(scope, attr.iterator().next());
            } else if (attr != null && attr.size() > 1) {
                // add a set to the response
                response.put(scope, attr);
            } else {
                //attr is null or attr is empty
                logger.warning("ScopeImpl.getUserInfo(): Got an empty result for attribute=" + attributes + " of scope=" + scope);
            }
        } else if (attributes instanceof Map) {
            //for example profile can be address, email, etc...
            if (attributes != null && !((Map<String, String>) attributes).isEmpty()) {
                for (Map.Entry<String, String> entry : ((Map<String, String>) attributes).entrySet()) {
                    String attribute;
                    attribute = entry.getValue();
                    Set<String> attr = null;
                    //get the attribute
                    try {
                        attr = id.getAttribute(attribute);
                    } catch (IdRepoException e) {
                        logger.warning("ScopeImpl.getUserInfo(): Unable to retrieve attribute", e);
                    } catch (SSOException e) {
                        logger.warning("ScopeImpl.getUserInfo(): Unable to retrieve attribute", e);
                    }
                    //add the attribute value(s) to the response
                    if (attr != null && attr.size() == 1) {
                        response.put(entry.getKey(), attr.iterator().next());
                    } else if (attr != null && attr.size() > 1) {
                        response.put(entry.getKey(), attr);
                    } else {
                        //attr is null or attr is empty
                        logger.warning("ScopeImpl.getUserInfo(): Got an empty result for scope=" + scope);
                    }
                }
            }
        }
    }
    return new UserInfoClaims(response, Collections.<String, List<String>>emptyMap());
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) UserInfoClaims(org.forgerock.oauth2.core.UserInfoClaims) AMIdentity(com.sun.identity.idm.AMIdentity) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 43 with Token

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

the class ScopeImpl method evaluateScope.

/**
     * {@inheritDoc}
     */
public Map<String, Object> evaluateScope(CoreToken token) {
    final Map<String, Object> map = new HashMap<String, Object>();
    final Set<String> scopes = token.getScope();
    final String clientId = token.getClientID();
    final String resourceOwner = token.getUserID();
    final String grantType = token.getGrantType();
    AMIdentity id = null;
    try {
        if (clientId != null && OAuth2Constants.TokenEndpoint.CLIENT_CREDENTIALS.equals(grantType)) {
            id = identityManager.getClientIdentity(clientId, token.getRealm());
        } else if (resourceOwner != null) {
            id = identityManager.getResourceOwnerIdentity(resourceOwner, token.getRealm());
        }
    } catch (UnauthorizedClientException e) {
        logger.error("Unable to get user identity", e);
    }
    if (id == null || scopes.isEmpty()) {
        return map;
    }
    try {
        for (final String scope : scopes) {
            final Set<String> attributes = id.getAttribute(scope);
            if (attributes != null) {
                final Iterator<String> iter = attributes.iterator();
                final StringBuilder builder = new StringBuilder();
                while (iter.hasNext()) {
                    builder.append(iter.next());
                    if (iter.hasNext()) {
                        builder.append(MULTI_ATTRIBUTE_SEPARATOR);
                    }
                }
                map.put(scope, builder.toString());
            }
        }
    } catch (SSOException e) {
        logger.error("Unable to get attribute", e);
    } catch (IdRepoException e) {
        logger.error("Unable to get attribute", e);
    }
    return map;
}
Also used : HashMap(java.util.HashMap) AMIdentity(com.sun.identity.idm.AMIdentity) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException)

Example 44 with Token

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

the class OpenAMResourceSetStore method update.

@Override
public void update(ResourceSetDescription resourceSetDescription) throws NotFoundException, ServerException {
    try {
        if (!realm.equals(resourceSetDescription.getRealm())) {
            throw new ServerException("Could not read token with id, " + resourceSetDescription.getId() + ", in realm, " + realm);
        }
        read(resourceSetDescription.getId(), resourceSetDescription.getResourceOwnerId());
        delegate.update(resourceSetDescription);
    } catch (org.forgerock.openam.sm.datalayer.store.NotFoundException e) {
        throw new NotFoundException("Resource set does not exist with id " + resourceSetDescription.getId());
    } catch (org.forgerock.openam.sm.datalayer.store.ServerException e) {
        throw new ServerException(e);
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException)

Example 45 with Token

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

the class OpenAMTokenStore method createRefreshToken.

@Override
public RefreshToken createRefreshToken(String grantType, String clientId, String resourceOwnerId, String redirectUri, Set<String> scope, OAuth2Request request, String validatedClaims) throws ServerException, NotFoundException {
    final String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    logger.message("Create refresh token");
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();
    final long lifeTime;
    if (clientRegistration == null) {
        lifeTime = providerSettings.getRefreshTokenLifetime();
    } else {
        lifeTime = clientRegistration.getRefreshTokenLifeTime(providerSettings);
    }
    long expiryTime = lifeTime < 0 ? -1 : lifeTime + System.currentTimeMillis();
    AuthorizationCode token = request.getToken(AuthorizationCode.class);
    String authModules = null;
    String acr = null;
    if (token != null) {
        authModules = token.getAuthModules();
        acr = token.getAuthenticationContextClassReference();
    }
    RefreshToken currentRefreshToken = request.getToken(RefreshToken.class);
    if (currentRefreshToken != null) {
        authModules = currentRefreshToken.getAuthModules();
        acr = currentRefreshToken.getAuthenticationContextClassReference();
    }
    OpenAMRefreshToken refreshToken = new OpenAMRefreshToken(id, resourceOwnerId, clientId, redirectUri, scope, expiryTime, OAuth2Constants.Bearer.BEARER, OAuth2Constants.Token.OAUTH_REFRESH_TOKEN, grantType, realm, authModules, acr, auditId);
    if (!StringUtils.isBlank(validatedClaims)) {
        refreshToken.setClaims(validatedClaims);
    }
    try {
        tokenStore.create(refreshToken);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_REFRESH_TOKEN", refreshToken.toString() };
            auditLogger.logAccessMessage("CREATED_REFRESH_TOKEN", obs, null);
        }
    } catch (CoreTokenException e) {
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_REFRESH_TOKEN", refreshToken.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_REFRESH_TOKEN", obs, null);
        }
        logger.error("Unable to create refresh token: " + refreshToken.getTokenInfo(), e);
        throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }
    request.setToken(RefreshToken.class, refreshToken);
    return refreshToken;
}
Also used : AuthorizationCode(org.forgerock.oauth2.core.AuthorizationCode) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) RefreshToken(org.forgerock.oauth2.core.RefreshToken) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Aggregations

ServerException (org.forgerock.oauth2.core.exceptions.ServerException)33 JsonValue (org.forgerock.json.JsonValue)22 AccessToken (org.forgerock.oauth2.core.AccessToken)18 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)18 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)18 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)18 SSOException (com.iplanet.sso.SSOException)16 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)16 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)16 SSOToken (com.iplanet.sso.SSOToken)13 AMIdentity (com.sun.identity.idm.AMIdentity)12 IdRepoException (com.sun.identity.idm.IdRepoException)11 Set (java.util.Set)9 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)9 HashMap (java.util.HashMap)8 HashSet (java.util.HashSet)8 InvalidGrantException (org.forgerock.oauth2.core.exceptions.InvalidGrantException)8 Test (org.testng.annotations.Test)8 Map (java.util.Map)6 AccessTokenVerifier (org.forgerock.oauth2.core.AccessTokenVerifier)6