Search in sources :

Example 26 with SignatureException

use of java.security.SignatureException 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 27 with SignatureException

use of java.security.SignatureException in project robovm by robovm.

the class Signature2Test method test_verify$BII.

/**
     * java.security.Signature#verify(byte[], int, int)
     */
public void test_verify$BII() throws Exception {
    Signature sig = Signature.getInstance("DSA");
    sig.initSign(getDsaKeys().getPrivate());
    sig.update(MESSAGE.getBytes());
    byte[] signature = sig.sign();
    sig.initVerify(getDsaKeys().getPublic());
    sig.update(MESSAGE.getBytes());
    assertTrue("Sign/Verify does not pass", sig.verify(signature, 0, signature.length));
    try {
        sig.verify(null, 0, signature.length);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
        sig.verify(signature, -5, signature.length);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    if (StandardNames.IS_RI) {
        try {
            sig.verify(signature, signature.length, 0);
            fail();
        } catch (SignatureException expected) {
        }
    } else {
        // Calling Signature.verify a second time should not throw
        // http://code.google.com/p/android/issues/detail?id=34933
        boolean verified = sig.verify(signature, signature.length, 0);
        assertFalse(verified);
    }
    try {
        sig.verify(signature, 0, signature.length * 2);
        fail();
    } catch (IllegalArgumentException expected) {
    }
}
Also used : Signature(java.security.Signature) SignatureException(java.security.SignatureException)

Example 28 with SignatureException

use of java.security.SignatureException in project robovm by robovm.

the class Signature2Test method test_verify$B.

/**
     * java.security.Signature#verify(byte[])
     */
public void test_verify$B() throws Exception {
    Signature sig = Signature.getInstance("DSA");
    try {
        sig.verify(new byte[] { 0, 1, 2, 3 });
        fail();
    } catch (SignatureException expected) {
    }
    sig.initSign(getDsaKeys().getPrivate());
    sig.update(MESSAGE.getBytes());
    byte[] signature = sig.sign();
    sig.initVerify(getDsaKeys().getPublic());
    sig.update(MESSAGE.getBytes());
    assertTrue("Sign/Verify does not pass", sig.verify(signature));
}
Also used : Signature(java.security.Signature) SignatureException(java.security.SignatureException)

Example 29 with SignatureException

use of java.security.SignatureException in project robovm by robovm.

the class SignatureExceptionTest method testSignatureException09.

/**
     * Test for <code>SignatureException(String, Throwable)</code> constructor
     * Assertion: constructs SignatureException when <code>cause</code> is not
     * null <code>msg</code> is not null
     */
public void testSignatureException09() {
    SignatureException tE;
    for (int i = 0; i < msgs.length; i++) {
        tE = new SignatureException(msgs[i], tCause);
        String getM = tE.getMessage();
        String toS = tCause.toString();
        if (msgs[i].length() > 0) {
            assertTrue("getMessage() must contain ".concat(msgs[i]), getM.indexOf(msgs[i]) != -1);
            if (!getM.equals(msgs[i])) {
                assertTrue("getMessage() should contain ".concat(toS), getM.indexOf(toS) != -1);
            }
        }
        assertNotNull("getCause() must not return null", tE.getCause());
        assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause);
    }
}
Also used : SignatureException(java.security.SignatureException)

Example 30 with SignatureException

use of java.security.SignatureException in project robovm by robovm.

the class SignatureExceptionTest method testSignatureException01.

/**
     * Test for <code>SignatureException()</code> constructor Assertion:
     * constructs SignatureException with no detail message
     */
public void testSignatureException01() {
    SignatureException tE = new SignatureException();
    assertNull("getMessage() must return null.", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
Also used : SignatureException(java.security.SignatureException)

Aggregations

SignatureException (java.security.SignatureException)329 InvalidKeyException (java.security.InvalidKeyException)171 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)132 Signature (java.security.Signature)132 IOException (java.io.IOException)75 PublicKey (java.security.PublicKey)53 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)39 X509Certificate (java.security.cert.X509Certificate)33 BigInteger (java.math.BigInteger)32 CertificateException (java.security.cert.CertificateException)31 NoSuchProviderException (java.security.NoSuchProviderException)29 PrivateKey (java.security.PrivateKey)25 ByteArrayInputStream (java.io.ByteArrayInputStream)17 KeyFactory (java.security.KeyFactory)15 ArrayList (java.util.ArrayList)15 MySignature1 (org.apache.harmony.security.tests.support.MySignature1)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)12 GeneralSecurityException (java.security.GeneralSecurityException)12 MessageDigest (java.security.MessageDigest)12