Search in sources :

Example 16 with ResourceOwner

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

the class OpenAMResourceOwnerSessionValidator method validate.

/**
     * {@inheritDoc}
     */
public ResourceOwner validate(OAuth2Request request) throws ResourceOwnerAuthenticationRequired, AccessDeniedException, BadRequestException, InteractionRequiredException, LoginRequiredException, ServerException, NotFoundException {
    final OpenIdPrompt openIdPrompt = new OpenIdPrompt(request);
    if (!openIdPrompt.isValid()) {
        String message = "Invalid prompt parameter \"" + openIdPrompt.getOriginalValue() + "\"";
        logger.message(message);
        throw new BadRequestException(message);
    }
    SSOToken token = null;
    try {
        token = ssoTokenManager.createSSOToken(getHttpServletRequest(request.<Request>getRequest()));
    } catch (SSOException e) {
        logger.warning("Error authenticating user against OpenAM: ", e);
    }
    try {
        if (token == null) {
            token = ssoTokenManager.createSSOToken(request.getSession());
        }
    } catch (SSOException e) {
        logger.warning("Error authenticating user against OpenAM: ", e);
    }
    try {
        if (token != null) {
            try {
                // As the organization in the token is stored in lowercase, we need to lower case the auth2realm
                String auth2Realm = dnWrapper.orgNameToDN(realmNormaliser.normalise((String) request.getParameter("realm"))).toLowerCase();
                String tokenRealm = token.getProperty("Organization");
                // auth2Realm can't be null as we would have an error earlier
                if (!auth2Realm.equals(tokenRealm)) {
                    throw authenticationRequired(request);
                }
            } catch (SSOException e) {
                throw new AccessDeniedException(e);
            }
            if (openIdPrompt.containsLogin()) {
                throw authenticationRequired(request, token);
            }
            final String acrValuesStr = request.getParameter(ACR_VALUES);
            if (acrValuesStr != null) {
                setCurrentAcr(token, request, acrValuesStr);
            }
            try {
                final long authTime = stringToDate(token.getProperty(ISAuthConstants.AUTH_INSTANT)).getTime();
                if (isPastMaxAge(getMaxAge(request), authTime)) {
                    alterMaxAge(request);
                    throw authenticationRequired(request, token);
                }
                final AMIdentity id = IdUtils.getIdentity(AccessController.doPrivileged(AdminTokenAction.getInstance()), token.getProperty(Constants.UNIVERSAL_IDENTIFIER));
                return new OpenAMResourceOwner(id.getName(), id, authTime);
            } catch (Exception e) {
                //Exception as chance of MANY exception types here.
                logger.error("Error authenticating user against OpenAM: ", e);
                throw new LoginRequiredException();
            }
        } else if (PASSWORD.equals(request.getParameter(GRANT_TYPE))) {
            // been null from the attempted creation in L148.
            return getResourceOwner(request.getToken(AccessToken.class));
        } else {
            if (openIdPrompt.containsNone()) {
                logger.error("Not pre-authenticated and prompt parameter equals none.");
                if (request.getParameter(OAuth2Constants.Params.RESPONSE_TYPE) != null) {
                    throw new InteractionRequiredException(Utils.isOpenIdConnectFragmentErrorType(splitResponseType(request.<String>getParameter(RESPONSE_TYPE))) ? FRAGMENT : QUERY);
                } else {
                    throw new InteractionRequiredException();
                }
            } else if (!isRefreshToken(request)) {
                throw authenticationRequired(request);
            } else {
                return getResourceOwner(request.getToken(RefreshToken.class));
            }
        }
    } catch (SSOException | UnsupportedEncodingException | URISyntaxException e) {
        throw new AccessDeniedException(e);
    }
}
Also used : LoginRequiredException(org.forgerock.oauth2.core.exceptions.LoginRequiredException) InteractionRequiredException(org.forgerock.oauth2.core.exceptions.InteractionRequiredException) AccessDeniedException(org.forgerock.oauth2.core.exceptions.AccessDeniedException) SSOToken(com.iplanet.sso.SSOToken) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSOException(com.iplanet.sso.SSOException) URISyntaxException(java.net.URISyntaxException) OpenIdPrompt(org.forgerock.openidconnect.OpenIdPrompt) URISyntaxException(java.net.URISyntaxException) InvalidClientAuthZHeaderException(org.forgerock.oauth2.core.exceptions.InvalidClientAuthZHeaderException) ParseException(java.text.ParseException) EncodingException(org.owasp.esapi.errors.EncodingException) 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) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TemplateException(freemarker.template.TemplateException) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) LoginRequiredException(org.forgerock.oauth2.core.exceptions.LoginRequiredException) InteractionRequiredException(org.forgerock.oauth2.core.exceptions.InteractionRequiredException) IOException(java.io.IOException) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) AccessDeniedException(org.forgerock.oauth2.core.exceptions.AccessDeniedException) RefreshToken(org.forgerock.oauth2.core.RefreshToken) AMIdentity(com.sun.identity.idm.AMIdentity) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException)

Example 17 with ResourceOwner

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

the class OpenAMResourceOwnerAuthenticator method authenticate.

private ResourceOwner authenticate(String username, char[] password, String realm, String service) {
    ResourceOwner ret = null;
    AuthContext lc = null;
    try {
        lc = new AuthContext(realm);
        if (service != null) {
            lc.login(AuthContext.IndexType.SERVICE, service, null, ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
        } else {
            lc.login(ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
        }
        while (lc.hasMoreRequirements()) {
            Callback[] callbacks = lc.getRequirements();
            ArrayList missing = new ArrayList();
            // loop through the requires setting the needs..
            for (int i = 0; i < callbacks.length; i++) {
                if (callbacks[i] instanceof NameCallback) {
                    NameCallback nc = (NameCallback) callbacks[i];
                    nc.setName(username);
                } else if (callbacks[i] instanceof PasswordCallback) {
                    PasswordCallback pc = (PasswordCallback) callbacks[i];
                    pc.setPassword(password);
                } else {
                    missing.add(callbacks[i]);
                }
            }
            // there's missing requirements not filled by this
            if (missing.size() > 0) {
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Missing requirements");
            }
            lc.submitRequirements(callbacks);
        }
        // validate the password..
        if (lc.getStatus() == AuthContext.Status.SUCCESS) {
            try {
                // package up the token for transport..
                ret = createResourceOwner(lc);
            } catch (Exception e) {
                logger.error("Unable to get SSOToken", e);
                // because the system is likely down..
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
            }
        }
    } catch (AuthLoginException le) {
        logger.error("AuthException", le);
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, le);
    } finally {
        if (lc != null && AuthContext.Status.SUCCESS.equals(lc.getStatus())) {
            try {
                lc.logout();
                logger.message("Logged user out.");
            } catch (AuthLoginException e) {
                logger.error("Exception caught logging out of AuthContext after successful login", e);
            }
        }
    }
    return ret;
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) ArrayList(java.util.ArrayList) AuthContext(com.sun.identity.authentication.AuthContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) ResourceException(org.restlet.resource.ResourceException) IdRepoException(com.sun.identity.idm.IdRepoException) ResourceException(org.restlet.resource.ResourceException) ParseException(java.text.ParseException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

Example 18 with ResourceOwner

use of org.forgerock.oauth2.core.ResourceOwner 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)

Example 19 with ResourceOwner

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

the class TokenResponseType method createToken.

public CoreToken createToken(Token accessToken, Map<String, Object> data) throws NotFoundException {
    final String tokenType = (String) data.get(OAuth2Constants.CoreTokenParams.TOKEN_TYPE);
    final Set<String> scope = (Set<String>) data.get(OAuth2Constants.CoreTokenParams.SCOPE);
    final OAuth2Request request = requestFactory.create(Request.getCurrent());
    final ResourceOwner resourceOwner = ownerAuthenticator.authenticate(request, true);
    final String clientId = (String) data.get(OAuth2Constants.CoreTokenParams.CLIENT_ID);
    final String redirectUri = (String) data.get(OAuth2Constants.CoreTokenParams.REDIRECT_URI);
    final String codeChallenge = (String) data.get(OAuth2Constants.Custom.CODE_CHALLENGE);
    final String codeChallengeMethod = (String) data.get(OAuth2Constants.Custom.CODE_CHALLENGE_METHOD);
    try {
        final Map.Entry<String, Token> tokenEntry = handler.handle(tokenType, scope, resourceOwner, clientId, redirectUri, null, requestFactory.create(Request.getCurrent()), codeChallenge, codeChallengeMethod);
        return new LegacyAccessTokenAdapter((AccessToken) tokenEntry.getValue());
    } catch (ServerException e) {
        throw OAuthProblemException.OAuthError.SERVER_ERROR.handle(Request.getCurrent(), e.getMessage());
    }
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Set(java.util.Set) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) LegacyAccessTokenAdapter(org.forgerock.openam.oauth2.legacy.LegacyAccessTokenAdapter) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) Token(org.forgerock.oauth2.core.Token) CoreToken(org.forgerock.openam.oauth2.legacy.CoreToken) AccessToken(org.forgerock.oauth2.core.AccessToken) Map(java.util.Map)

Example 20 with ResourceOwner

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

the class AuthorizationRequestEndpoint method requestAuthorization.

@Post
public Representation requestAuthorization(JsonRepresentation entity) throws BadRequestException, UmaException, EntitlementException, ServerException, NotFoundException {
    UmaProviderSettings umaProviderSettings = umaProviderSettingsFactory.get(this.getRequest());
    final OAuth2Request oauth2Request = requestFactory.create(getRequest());
    OAuth2ProviderSettings oauth2ProviderSettings = oauth2ProviderSettingsFactory.get(oauth2Request);
    OAuth2Uris oAuth2Uris = oAuth2UrisFactory.get(oauth2Request);
    final UmaTokenStore umaTokenStore = umaProviderSettings.getUmaTokenStore();
    String realm = oauth2Request.getParameter("realm");
    JsonValue requestBody = json(toMap(entity));
    PermissionTicket permissionTicket = getPermissionTicket(umaTokenStore, requestBody);
    validatePermissionTicketHolder(umaTokenStore, permissionTicket);
    final String resourceSetId = permissionTicket.getResourceSetId();
    final Request request = getRequest();
    final String resourceOwnerId = getResourceOwnerId(oauth2ProviderSettings, resourceSetId);
    AMIdentity resourceOwner = createIdentity(resourceOwnerId, realm);
    String requestingPartyId = null;
    try {
        requestingPartyId = getRequestingPartyId(umaProviderSettings, oAuth2Uris, requestBody);
    } finally {
        auditLogger.log(resourceSetId, resourceOwner, UmaAuditType.REQUEST, request, requestingPartyId == null ? getAuthorisationApiToken().getResourceOwnerId() : requestingPartyId);
    }
    if (isEntitled(umaProviderSettings, oauth2ProviderSettings, permissionTicket, requestingPartyId)) {
        getResponse().setStatus(new Status(200));
        auditLogger.log(resourceSetId, resourceOwner, UmaAuditType.GRANTED, request, requestingPartyId);
        return createJsonRpt(umaTokenStore, permissionTicket);
    } else {
        try {
            if (verifyPendingRequestDoesNotAlreadyExist(resourceSetId, resourceOwnerId, permissionTicket.getRealm(), requestingPartyId, permissionTicket.getScopes())) {
                auditLogger.log(resourceSetId, resourceOwner, UmaAuditType.DENIED, request, requestingPartyId);
                throw new UmaException(403, UmaConstants.NOT_AUTHORISED_ERROR_CODE, "The client is not authorised to access the requested resource set");
            } else {
                pendingRequestsService.createPendingRequest(ServletUtils.getRequest(getRequest()), resourceSetId, auditLogger.getResourceName(resourceSetId, request), resourceOwnerId, requestingPartyId, permissionTicket.getRealm(), permissionTicket.getScopes());
                auditLogger.log(resourceSetId, resourceOwner, UmaAuditType.REQUEST_SUBMITTED, request, requestingPartyId);
            }
        } catch (org.forgerock.openam.sm.datalayer.store.ServerException e) {
            logger.error("Failed to create pending request", e);
            throw new UmaException(403, UmaConstants.NOT_AUTHORISED_ERROR_CODE, "Failed to create pending request");
        }
        throw newRequestSubmittedException();
    }
}
Also used : Status(org.restlet.data.Status) OAuth2Uris(org.forgerock.oauth2.core.OAuth2Uris) JsonValue(org.forgerock.json.JsonValue) UmaPendingRequest(org.forgerock.openam.sm.datalayer.impl.uma.UmaPendingRequest) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) Request(org.restlet.Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AMIdentity(com.sun.identity.idm.AMIdentity) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) Post(org.restlet.resource.Post)

Aggregations

ServerException (org.forgerock.oauth2.core.exceptions.ServerException)11 ResourceOwner (org.forgerock.oauth2.core.ResourceOwner)8 SSOException (com.iplanet.sso.SSOException)7 AMIdentity (com.sun.identity.idm.AMIdentity)7 IdRepoException (com.sun.identity.idm.IdRepoException)6 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)6 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)6 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)6 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)6 UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)6 ParseException (java.text.ParseException)4 SMSException (com.sun.identity.sm.SMSException)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 DeviceCode (org.forgerock.oauth2.core.DeviceCode)3 SSOToken (com.iplanet.sso.SSOToken)2 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)2 Set (java.util.Set)2 AccessToken (org.forgerock.oauth2.core.AccessToken)2