Search in sources :

Example 1 with GrantType

use of org.xdi.oxauth.model.common.GrantType in project oxAuth by GluuFederation.

the class TokenRestWebServiceImpl method requestAccessToken.

@Override
public Response requestAccessToken(String grantType, String code, String redirectUri, String username, String password, String scope, String assertion, String refreshToken, String oxAuthExchangeToken, String clientId, String clientSecret, String codeVerifier, HttpServletRequest request, SecurityContext sec) {
    log.debug("Attempting to request access token: grantType = {}, code = {}, redirectUri = {}, username = {}, refreshToken = {}, " + "clientId = {}, ExtraParams = {}, isSecure = {}, codeVerifier = {}", grantType, code, redirectUri, username, refreshToken, clientId, request.getParameterMap(), sec.isSecure(), codeVerifier);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REQUEST);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setUsername(username);
    oAuth2AuditLog.setScope(scope);
    // it may be encoded in uma case
    scope = ServerUtil.urlDecode(scope);
    ResponseBuilder builder = Response.ok();
    try {
        log.debug("Starting to validate request parameters");
        if (!TokenParamsValidator.validateParams(grantType, code, redirectUri, username, password, scope, assertion, refreshToken, oxAuthExchangeToken)) {
            log.trace("Failed to validate request parameters");
            builder = error(400, TokenErrorResponseType.INVALID_REQUEST);
        } else {
            log.trace("Request parameters are right");
            GrantType gt = GrantType.fromString(grantType);
            log.debug("Grant type: '{}'", gt);
            SessionClient sessionClient = identity.getSetSessionClient();
            Client client = null;
            if (sessionClient != null) {
                client = sessionClient.getClient();
                log.debug("Get sessionClient: '{}'", sessionClient);
            }
            if (client != null) {
                log.debug("Get client from session: '{}'", client.getClientId());
            }
            if (gt == GrantType.AUTHORIZATION_CODE) {
                if (client == null) {
                    return response(error(400, TokenErrorResponseType.INVALID_GRANT));
                }
                log.debug("Attempting to find authorizationCodeGrant by clinetId: '{}', code: '{}'", client.getClientId(), code);
                AuthorizationCodeGrant authorizationCodeGrant = authorizationGrantList.getAuthorizationCodeGrant(client.getClientId(), code);
                log.trace("AuthorizationCodeGrant : '{}'", authorizationCodeGrant);
                if (authorizationCodeGrant != null) {
                    validatePKCE(authorizationCodeGrant, codeVerifier);
                    authorizationCodeGrant.setIsCachedWithNoPersistence(false);
                    authorizationCodeGrant.save();
                    AccessToken accToken = authorizationCodeGrant.createAccessToken();
                    log.debug("Issuing access token: {}", accToken.getCode());
                    RefreshToken reToken = authorizationCodeGrant.createRefreshToken();
                    if (scope != null && !scope.isEmpty()) {
                        scope = authorizationCodeGrant.checkScopesPolicy(scope);
                    }
                    IdToken idToken = null;
                    if (authorizationCodeGrant.getScopes().contains("openid")) {
                        String nonce = authorizationCodeGrant.getNonce();
                        boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                        idToken = authorizationCodeGrant.createIdToken(nonce, null, accToken, authorizationCodeGrant, includeIdTokenClaims);
                    }
                    builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, idToken));
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationCodeGrant, true);
                    grantService.removeByCode(authorizationCodeGrant.getAuthorizationCode().getCode(), authorizationCodeGrant.getClientId());
                } else {
                    log.debug("AuthorizationCodeGrant is empty by clinetId: '{}', code: '{}'", client.getClientId(), code);
                    // if authorization code is not found then code was already used = remove all grants with this auth code
                    grantService.removeAllByAuthorizationCode(code);
                    builder = error(400, TokenErrorResponseType.INVALID_GRANT);
                }
            } else if (gt == GrantType.REFRESH_TOKEN) {
                if (client == null) {
                    return response(error(401, TokenErrorResponseType.INVALID_GRANT));
                }
                AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), refreshToken);
                if (authorizationGrant != null) {
                    AccessToken accToken = authorizationGrant.createAccessToken();
                    /*
                        The authorization server MAY issue a new refresh token, in which case
                        the client MUST discard the old refresh token and replace it with the
                        new refresh token.
                        */
                    RefreshToken reToken = authorizationGrant.createRefreshToken();
                    grantService.removeByCode(refreshToken, client.getClientId());
                    if (scope != null && !scope.isEmpty()) {
                        scope = authorizationGrant.checkScopesPolicy(scope);
                    }
                    builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, null));
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                } else {
                    builder = error(401, TokenErrorResponseType.INVALID_GRANT);
                }
            } else if (gt == GrantType.CLIENT_CREDENTIALS) {
                if (client == null) {
                    return response(error(401, TokenErrorResponseType.INVALID_GRANT));
                }
                // TODO: fix the user arg
                ClientCredentialsGrant clientCredentialsGrant = authorizationGrantList.createClientCredentialsGrant(new User(), client);
                AccessToken accessToken = clientCredentialsGrant.createAccessToken();
                if (scope != null && !scope.isEmpty()) {
                    scope = clientCredentialsGrant.checkScopesPolicy(scope);
                }
                IdToken idToken = null;
                if (clientCredentialsGrant.getScopes().contains("openid")) {
                    boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                    idToken = clientCredentialsGrant.createIdToken(null, null, null, clientCredentialsGrant, includeIdTokenClaims);
                }
                oAuth2AuditLog.updateOAuth2AuditLog(clientCredentialsGrant, true);
                builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, scope, idToken));
            } else if (gt == GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS) {
                if (client == null) {
                    log.error("Invalid client", new RuntimeException("Client is empty"));
                    return response(error(401, TokenErrorResponseType.INVALID_CLIENT));
                }
                User user = null;
                if (authenticationFilterService.isEnabled()) {
                    String userDn = authenticationFilterService.processAuthenticationFilters(request.getParameterMap());
                    if (StringHelper.isNotEmpty(userDn)) {
                        user = userService.getUserByDn(userDn);
                    }
                }
                if (user == null) {
                    boolean authenticated = authenticationService.authenticate(username, password);
                    if (authenticated) {
                        user = authenticationService.getAuthenticatedUser();
                    }
                }
                if (user != null) {
                    ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = authorizationGrantList.createResourceOwnerPasswordCredentialsGrant(user, client);
                    AccessToken accessToken = resourceOwnerPasswordCredentialsGrant.createAccessToken();
                    RefreshToken reToken = resourceOwnerPasswordCredentialsGrant.createRefreshToken();
                    if (scope != null && !scope.isEmpty()) {
                        scope = resourceOwnerPasswordCredentialsGrant.checkScopesPolicy(scope);
                    }
                    IdToken idToken = null;
                    if (resourceOwnerPasswordCredentialsGrant.getScopes().contains("openid")) {
                        boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                        idToken = resourceOwnerPasswordCredentialsGrant.createIdToken(null, null, null, resourceOwnerPasswordCredentialsGrant, includeIdTokenClaims);
                    }
                    oAuth2AuditLog.updateOAuth2AuditLog(resourceOwnerPasswordCredentialsGrant, true);
                    builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), reToken, scope, idToken));
                } else {
                    log.error("Invalid user", new RuntimeException("User is empty"));
                    builder = error(401, TokenErrorResponseType.INVALID_CLIENT);
                }
            } else if (gt == GrantType.EXTENSION) {
                builder = error(501, TokenErrorResponseType.INVALID_GRANT);
            } else if (gt == GrantType.OXAUTH_EXCHANGE_TOKEN) {
                AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(oxAuthExchangeToken);
                if (authorizationGrant != null) {
                    final AccessToken accessToken = authorizationGrant.createLongLivedAccessToken();
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                    builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, null, null));
                } else {
                    builder = error(401, TokenErrorResponseType.INVALID_GRANT);
                }
            }
        }
    } catch (WebApplicationException e) {
        throw e;
    } catch (SignatureException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (StringEncrypter.EncryptionException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (InvalidJwtException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (InvalidJweException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return response(builder);
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) IdToken(org.xdi.oxauth.model.common.IdToken) User(org.xdi.oxauth.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(org.xdi.oxauth.model.session.SessionClient) OAuth2AuditLog(org.xdi.oxauth.model.audit.OAuth2AuditLog) ResourceOwnerPasswordCredentialsGrant(org.xdi.oxauth.model.common.ResourceOwnerPasswordCredentialsGrant) GrantType(org.xdi.oxauth.model.common.GrantType) SignatureException(java.security.SignatureException) StringEncrypter(org.xdi.util.security.StringEncrypter) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SignatureException(java.security.SignatureException) JSONException(org.codehaus.jettison.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) RefreshToken(org.xdi.oxauth.model.common.RefreshToken) AuthorizationCodeGrant(org.xdi.oxauth.model.common.AuthorizationCodeGrant) AccessToken(org.xdi.oxauth.model.common.AccessToken) ClientCredentialsGrant(org.xdi.oxauth.model.common.ClientCredentialsGrant) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Client(org.xdi.oxauth.model.registration.Client) SessionClient(org.xdi.oxauth.model.session.SessionClient) AuthorizationGrant(org.xdi.oxauth.model.common.AuthorizationGrant) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException)

Example 2 with GrantType

use of org.xdi.oxauth.model.common.GrantType in project oxAuth by GluuFederation.

the class AcceptValidAsymmetricIdTokenSignature method acceptValidAsymmetricIdTokenSignatureES256.

@Parameters({ "redirectUris", "userId", "userSecret", "redirectUri", "postLogoutRedirectUri", "clientJwksUri" })
@Test
public void acceptValidAsymmetricIdTokenSignatureES256(final String redirectUris, final String userId, final String userSecret, final String redirectUri, final String postLogoutRedirectUri, final String clientJwksUri) throws Exception {
    showTitle("OC5:FeatureTest-Accept Valid Asymmetric ID Token Signature es256");
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);
    List<GrantType> grantTypes = Arrays.asList(GrantType.AUTHORIZATION_CODE);
    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, null, StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.ES256);
    registerRequest.setPostLogoutRedirectUris(StringUtils.spaceSeparatedToList(postLogoutRedirectUri));
    registerRequest.setJwksUri(clientJwksUri);
    registerRequest.setSubjectType(SubjectType.PUBLIC);
    registerRequest.setRequireAuthTime(true);
    registerRequest.setDefaultMaxAge(3600);
    registerRequest.setGrantTypes(grantTypes);
    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();
    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientSecretExpiresAt());
    String clientId = registerResponse.getClientId();
    // 2. Request Authorization
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(state);
    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(authorizationEndpoint, authorizationRequest, userId, userSecret);
    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());
    assertEquals(authorizationResponse.getState(), state);
    String idToken = authorizationResponse.getIdToken();
    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    ECDSASigner ecdsaSigner = new ECDSASigner(SignatureAlgorithm.ES256, publicKey);
    assertTrue(ecdsaSigner.validate(jwt));
}
Also used : ECDSASigner(org.xdi.oxauth.model.jws.ECDSASigner) Jwt(org.xdi.oxauth.model.jwt.Jwt) GrantType(org.xdi.oxauth.model.common.GrantType) ResponseType(org.xdi.oxauth.model.common.ResponseType) ECDSAPublicKey(org.xdi.oxauth.model.crypto.signature.ECDSAPublicKey) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.xdi.oxauth.BaseTest)

Example 3 with GrantType

use of org.xdi.oxauth.model.common.GrantType in project oxAuth by GluuFederation.

the class TokenClient method execExtensionGrant.

/**
     * <p>
     * Executes the call to the REST Service requesting the authorization and
     * processes the response.
     * </p>
     * <p>
     * The client uses an extension grant type by specifying the grant type
     * using an absolute URI (defined by the authorization server) as the value
     * of the grant_type parameter of the token endpoint, and by adding any
     * additional parameters necessary.
     * </p>
     *
     * @param grantTypeUri Absolute URI.
     * @param assertion    Assertion grant type.
     * @param clientId     The client identifier.
     * @param clientSecret The client secret.
     * @return The token response.
     */
public TokenResponse execExtensionGrant(String grantTypeUri, String assertion, String clientId, String clientSecret) {
    GrantType grantType = GrantType.fromString(grantTypeUri);
    setRequest(new TokenRequest(grantType));
    getRequest().setAssertion(assertion);
    getRequest().setAuthUsername(clientId);
    getRequest().setAuthPassword(clientSecret);
    return exec();
}
Also used : GrantType(org.xdi.oxauth.model.common.GrantType)

Example 4 with GrantType

use of org.xdi.oxauth.model.common.GrantType in project oxAuth by GluuFederation.

the class RegisterRequest method fromJson.

public static RegisterRequest fromJson(String p_json) throws JSONException {
    final JSONObject requestObject = new JSONObject(p_json);
    final List<String> redirectUris = new ArrayList<String>();
    if (requestObject.has(REDIRECT_URIS.toString())) {
        JSONArray redirectUrisJsonArray = requestObject.getJSONArray(REDIRECT_URIS.toString());
        for (int i = 0; i < redirectUrisJsonArray.length(); i++) {
            String redirectionUri = redirectUrisJsonArray.getString(i);
            redirectUris.add(redirectionUri);
        }
    }
    final Set<ResponseType> responseTypes = new HashSet<ResponseType>();
    final Set<GrantType> grantTypes = new HashSet<GrantType>();
    if (requestObject.has(RESPONSE_TYPES.toString())) {
        JSONArray responseTypesJsonArray = requestObject.getJSONArray(RESPONSE_TYPES.toString());
        for (int i = 0; i < responseTypesJsonArray.length(); i++) {
            ResponseType rt = ResponseType.fromString(responseTypesJsonArray.getString(i));
            if (rt != null) {
                responseTypes.add(rt);
            }
        }
    } else {
        // Default
        responseTypes.add(ResponseType.CODE);
    }
    if (responseTypes.contains(ResponseType.CODE)) {
        grantTypes.add(GrantType.AUTHORIZATION_CODE);
    }
    if (responseTypes.contains(ResponseType.ID_TOKEN) || responseTypes.containsAll(Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN))) {
        grantTypes.add(GrantType.IMPLICIT);
    }
    if (responseTypes.containsAll(Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN)) || responseTypes.containsAll(Arrays.asList(ResponseType.CODE, ResponseType.TOKEN)) || responseTypes.containsAll(Arrays.asList(ResponseType.CODE, ResponseType.TOKEN, ResponseType.ID_TOKEN))) {
        grantTypes.add(GrantType.AUTHORIZATION_CODE);
        grantTypes.add(GrantType.IMPLICIT);
    }
    if (requestObject.has(GRANT_TYPES.toString())) {
        JSONArray grantTypesJsonArray = requestObject.getJSONArray(GRANT_TYPES.toString());
        for (int i = 0; i < grantTypesJsonArray.length(); i++) {
            GrantType gt = GrantType.fromString(grantTypesJsonArray.getString(i));
            if (gt != null) {
                grantTypes.add(gt);
                switch(gt) {
                    case AUTHORIZATION_CODE:
                        responseTypes.add(ResponseType.CODE);
                        break;
                    case IMPLICIT:
                        responseTypes.add(ResponseType.TOKEN);
                        responseTypes.add(ResponseType.ID_TOKEN);
                        break;
                    case REFRESH_TOKEN:
                        break;
                    default:
                        break;
                }
            }
        }
    } else {
        // Default
        grantTypes.add(GrantType.AUTHORIZATION_CODE);
    }
    final List<String> contacts = new ArrayList<String>();
    if (requestObject.has(CONTACTS.toString())) {
        JSONArray contactsJsonArray = requestObject.getJSONArray(CONTACTS.toString());
        for (int i = 0; i < contactsJsonArray.length(); i++) {
            contacts.add(contactsJsonArray.getString(i));
        }
    }
    final List<String> defaultAcrValues = new ArrayList<String>();
    if (requestObject.has(DEFAULT_ACR_VALUES.toString())) {
        JSONArray defaultAcrValuesJsonArray = requestObject.getJSONArray(DEFAULT_ACR_VALUES.toString());
        for (int i = 0; i < defaultAcrValuesJsonArray.length(); i++) {
            defaultAcrValues.add(defaultAcrValuesJsonArray.getString(i));
        }
    }
    final List<String> postLogoutRedirectUris = new ArrayList<String>();
    if (requestObject.has(POST_LOGOUT_REDIRECT_URIS.toString())) {
        JSONArray postLogoutRedirectUrisJsonArray = requestObject.getJSONArray(POST_LOGOUT_REDIRECT_URIS.toString());
        for (int i = 0; i < postLogoutRedirectUrisJsonArray.length(); i++) {
            postLogoutRedirectUris.add(postLogoutRedirectUrisJsonArray.getString(i));
        }
    }
    final List<String> requestUris = new ArrayList<String>();
    if (requestObject.has(REQUEST_URIS.toString())) {
        JSONArray requestUrisJsonArray = requestObject.getJSONArray(REQUEST_URIS.toString());
        for (int i = 0; i < requestUrisJsonArray.length(); i++) {
            requestUris.add(requestUrisJsonArray.getString(i));
        }
    }
    final List<String> scopes = new ArrayList<String>();
    if (requestObject.has(SCOPES.toString())) {
        JSONArray scopesJsonArray = requestObject.getJSONArray(SCOPES.toString());
        for (int i = 0; i < scopesJsonArray.length(); i++) {
            scopes.add(scopesJsonArray.getString(i));
        }
    }
    final List<String> frontChannelLogoutUris = new ArrayList<String>();
    if (requestObject.has(FRONT_CHANNEL_LOGOUT_URI.toString())) {
        try {
            JSONArray frontChannelLogoutUriJsonArray = requestObject.getJSONArray(FRONT_CHANNEL_LOGOUT_URI.toString());
            for (int i = 0; i < frontChannelLogoutUriJsonArray.length(); i++) {
                frontChannelLogoutUris.add(frontChannelLogoutUriJsonArray.getString(i));
            }
        } catch (JSONException e) {
            frontChannelLogoutUris.add(requestObject.optString(FRONT_CHANNEL_LOGOUT_URI.toString()));
        }
    }
    Date clientSecretExpiresAt = null;
    if (requestObject.has(CLIENT_SECRET_EXPIRES_AT_.getName())) {
        if (requestObject.optLong(CLIENT_SECRET_EXPIRES_AT_.getName()) > 0) {
            clientSecretExpiresAt = new Date(requestObject.optLong(CLIENT_SECRET_EXPIRES_AT_.getName()));
        }
    }
    final RegisterRequest result = new RegisterRequest();
    result.setJsonObject(requestObject);
    result.setClientSecretExpiresAt(clientSecretExpiresAt);
    result.setRequestUris(requestUris);
    result.setInitiateLoginUri(requestObject.optString(INITIATE_LOGIN_URI.toString()));
    result.setPostLogoutRedirectUris(postLogoutRedirectUris);
    result.setDefaultAcrValues(defaultAcrValues);
    result.setRequireAuthTime(requestObject.has(REQUIRE_AUTH_TIME.toString()) && requestObject.getBoolean(REQUIRE_AUTH_TIME.toString()));
    result.setFrontChannelLogoutUris(frontChannelLogoutUris);
    result.setFrontChannelLogoutSessionRequired(requestObject.optBoolean(FRONT_CHANNEL_LOGOUT_SESSION_REQUIRED.toString()));
    result.setDefaultMaxAge(requestObject.has(DEFAULT_MAX_AGE.toString()) ? requestObject.getInt(DEFAULT_MAX_AGE.toString()) : null);
    result.setIdTokenSignedResponseAlg(requestObject.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()) ? SignatureAlgorithm.fromString(requestObject.getString(ID_TOKEN_SIGNED_RESPONSE_ALG.toString())) : null);
    result.setIdTokenEncryptedResponseAlg(requestObject.has(ID_TOKEN_ENCRYPTED_RESPONSE_ALG.toString()) ? KeyEncryptionAlgorithm.fromName(requestObject.getString(ID_TOKEN_ENCRYPTED_RESPONSE_ALG.toString())) : null);
    result.setIdTokenEncryptedResponseEnc(requestObject.has(ID_TOKEN_ENCRYPTED_RESPONSE_ENC.toString()) ? BlockEncryptionAlgorithm.fromName(requestObject.getString(ID_TOKEN_ENCRYPTED_RESPONSE_ENC.toString())) : null);
    result.setUserInfoSignedResponseAlg(requestObject.has(USERINFO_SIGNED_RESPONSE_ALG.toString()) ? SignatureAlgorithm.fromString(requestObject.getString(USERINFO_SIGNED_RESPONSE_ALG.toString())) : null);
    result.setUserInfoEncryptedResponseAlg(requestObject.has(USERINFO_ENCRYPTED_RESPONSE_ALG.toString()) ? KeyEncryptionAlgorithm.fromName(requestObject.getString(USERINFO_ENCRYPTED_RESPONSE_ALG.toString())) : null);
    result.setUserInfoEncryptedResponseEnc(requestObject.has(USERINFO_ENCRYPTED_RESPONSE_ENC.toString()) ? BlockEncryptionAlgorithm.fromName(requestObject.getString(USERINFO_ENCRYPTED_RESPONSE_ENC.toString())) : null);
    result.setRequestObjectSigningAlg(requestObject.has(REQUEST_OBJECT_SIGNING_ALG.toString()) ? SignatureAlgorithm.fromString(requestObject.getString(REQUEST_OBJECT_SIGNING_ALG.toString())) : null);
    result.setRequestObjectEncryptionAlg(requestObject.has(REQUEST_OBJECT_ENCRYPTION_ALG.toString()) ? KeyEncryptionAlgorithm.fromName(requestObject.getString(REQUEST_OBJECT_ENCRYPTION_ALG.toString())) : null);
    result.setRequestObjectEncryptionEnc(requestObject.has(REQUEST_OBJECT_ENCRYPTION_ENC.toString()) ? BlockEncryptionAlgorithm.fromName(requestObject.getString(REQUEST_OBJECT_ENCRYPTION_ENC.toString())) : null);
    result.setTokenEndpointAuthMethod(requestObject.has(TOKEN_ENDPOINT_AUTH_METHOD.toString()) ? AuthenticationMethod.fromString(requestObject.getString(TOKEN_ENDPOINT_AUTH_METHOD.toString())) : null);
    result.setTokenEndpointAuthSigningAlg(requestObject.has(TOKEN_ENDPOINT_AUTH_SIGNING_ALG.toString()) ? SignatureAlgorithm.fromString(requestObject.getString(TOKEN_ENDPOINT_AUTH_SIGNING_ALG.toString())) : null);
    result.setRedirectUris(redirectUris);
    result.setScopes(scopes);
    result.setResponseTypes(new ArrayList<ResponseType>(responseTypes));
    result.setGrantTypes(new ArrayList<GrantType>(grantTypes));
    result.setApplicationType(requestObject.has(APPLICATION_TYPE.toString()) ? ApplicationType.fromString(requestObject.getString(APPLICATION_TYPE.toString())) : ApplicationType.WEB);
    result.setContacts(contacts);
    result.setClientName(requestObject.optString(CLIENT_NAME.toString()));
    result.setLogoUri(requestObject.optString(LOGO_URI.toString()));
    result.setClientUri(requestObject.optString(CLIENT_URI.toString()));
    result.setPolicyUri(requestObject.optString(POLICY_URI.toString()));
    result.setTosUri(requestObject.optString(TOS_URI.toString()));
    result.setJwksUri(requestObject.optString(JWKS_URI.toString()));
    result.setJwks(requestObject.optString(JWKS.toString()));
    result.setSectorIdentifierUri(requestObject.optString(SECTOR_IDENTIFIER_URI.toString()));
    result.setSubjectType(requestObject.has(SUBJECT_TYPE.toString()) ? SubjectType.fromString(requestObject.getString(SUBJECT_TYPE.toString())) : null);
    return result;
}
Also used : JSONArray(org.codehaus.jettison.json.JSONArray) StringUtils.toJSONArray(org.xdi.oxauth.model.util.StringUtils.toJSONArray) JSONException(org.codehaus.jettison.json.JSONException) GrantType(org.xdi.oxauth.model.common.GrantType) ResponseType(org.xdi.oxauth.model.common.ResponseType) JSONObject(org.codehaus.jettison.json.JSONObject)

Example 5 with GrantType

use of org.xdi.oxauth.model.common.GrantType in project oxAuth by GluuFederation.

the class TokenParamsValidator method validateParams.

/**
     * Validates the parameters for a token request.
     *
     * @param grantType    The grant type. This parameter is mandatory. Value must be set
     *                     to: <code>authorization_code</code>, <code>password</code>,
     *                     <code>client_credentials</code>, <code>refresh_token</code>,
     *                     or a valid {@link URI}.
     * @param code         The authorization code.
     * @param redirectUri
     * @param username
     * @param password
     * @param scope
     * @param assertion
     * @param refreshToken
     * @return Returns <code>true</code> when all the parameters are valid.
     */
public static boolean validateParams(String grantType, String code, String redirectUri, String username, String password, String scope, String assertion, String refreshToken, String oxAuthExchangeToken) {
    boolean result = false;
    if (grantType == null || grantType.isEmpty()) {
        return false;
    }
    GrantType gt = GrantType.fromString(grantType);
    switch(gt) {
        case AUTHORIZATION_CODE:
            result = code != null && !code.isEmpty() && redirectUri != null && !redirectUri.isEmpty();
            break;
        case RESOURCE_OWNER_PASSWORD_CREDENTIALS:
            result = true;
            break;
        case CLIENT_CREDENTIALS:
            result = true;
            break;
        case EXTENSION:
            result = assertion != null && !assertion.isEmpty();
            break;
        case REFRESH_TOKEN:
            result = refreshToken != null && !refreshToken.isEmpty();
            break;
        case OXAUTH_EXCHANGE_TOKEN:
            result = oxAuthExchangeToken != null && !oxAuthExchangeToken.isEmpty();
            break;
    }
    return result;
}
Also used : GrantType(org.xdi.oxauth.model.common.GrantType)

Aggregations

GrantType (org.xdi.oxauth.model.common.GrantType)5 JSONException (org.codehaus.jettison.json.JSONException)2 ResponseType (org.xdi.oxauth.model.common.ResponseType)2 SignatureException (java.security.SignatureException)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)1 JSONArray (org.codehaus.jettison.json.JSONArray)1 JSONObject (org.codehaus.jettison.json.JSONObject)1 Parameters (org.testng.annotations.Parameters)1 Test (org.testng.annotations.Test)1 BaseTest (org.xdi.oxauth.BaseTest)1 OAuth2AuditLog (org.xdi.oxauth.model.audit.OAuth2AuditLog)1 AccessToken (org.xdi.oxauth.model.common.AccessToken)1 AuthorizationCodeGrant (org.xdi.oxauth.model.common.AuthorizationCodeGrant)1 AuthorizationGrant (org.xdi.oxauth.model.common.AuthorizationGrant)1 ClientCredentialsGrant (org.xdi.oxauth.model.common.ClientCredentialsGrant)1 IdToken (org.xdi.oxauth.model.common.IdToken)1 RefreshToken (org.xdi.oxauth.model.common.RefreshToken)1 ResourceOwnerPasswordCredentialsGrant (org.xdi.oxauth.model.common.ResourceOwnerPasswordCredentialsGrant)1 User (org.xdi.oxauth.model.common.User)1