Search in sources :

Example 1 with SignatureAlgorithm

use of org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class BackchannelAuthorizeRestWebServiceImpl method requestBackchannelAuthorizationPost.

@Override
public Response requestBackchannelAuthorizationPost(String clientId, String scope, String clientNotificationToken, String acrValues, String loginHintToken, String idTokenHint, String loginHint, String bindingMessage, String userCodeParam, Integer requestedExpiry, String request, String requestUri, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    // it may be encoded
    scope = ServerUtil.urlDecode(scope);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.BACKCHANNEL_AUTHENTICATION);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setScope(scope);
    // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final,
    // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
    log.debug("Attempting to request backchannel authorization: " + "clientId = {}, scope = {}, clientNotificationToken = {}, acrValues = {}, loginHintToken = {}, " + "idTokenHint = {}, loginHint = {}, bindingMessage = {}, userCodeParam = {}, requestedExpiry = {}, " + "request= {}", clientId, scope, clientNotificationToken, acrValues, loginHintToken, idTokenHint, loginHint, bindingMessage, userCodeParam, requestedExpiry, request);
    log.debug("Attempting to request backchannel authorization: " + "isSecure = {}", securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    if (!appConfiguration.getCibaEnabled()) {
        log.warn("Trying to register a CIBA request, however CIBA config is disabled.");
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    SessionClient sessionClient = identity.getSessionClient();
    Client client = null;
    if (sessionClient != null) {
        client = sessionClient.getClient();
    }
    if (client == null) {
        // 401
        builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_CLIENT));
        return builder.build();
    }
    if (!cibaRequestService.hasCibaCompatibility(client)) {
        // 401
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    List<String> scopes = new ArrayList<>();
    if (StringHelper.isNotEmpty(scope)) {
        Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
        scopes.addAll(grantedScopes);
    }
    JwtAuthorizationRequest jwtRequest = null;
    if (StringUtils.isNotBlank(request) || StringUtils.isNotBlank(requestUri)) {
        jwtRequest = JwtAuthorizationRequest.createJwtRequest(request, requestUri, client, null, cryptoProvider, appConfiguration);
        if (jwtRequest == null) {
            log.error("The JWT couldn't be processed");
            // 400
            builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
            builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
            throw new WebApplicationException(builder.build());
        }
        authorizeRestWebServiceValidator.validateCibaRequestObject(jwtRequest, client.getClientId());
        // JWT wins
        if (!jwtRequest.getScopes().isEmpty()) {
            scopes.addAll(scopeChecker.checkScopesPolicy(client, jwtRequest.getScopes()));
        }
        if (StringUtils.isNotBlank(jwtRequest.getClientNotificationToken())) {
            clientNotificationToken = jwtRequest.getClientNotificationToken();
        }
        if (StringUtils.isNotBlank(jwtRequest.getAcrValues())) {
            acrValues = jwtRequest.getAcrValues();
        }
        if (StringUtils.isNotBlank(jwtRequest.getLoginHintToken())) {
            loginHintToken = jwtRequest.getLoginHintToken();
        }
        if (StringUtils.isNotBlank(jwtRequest.getIdTokenHint())) {
            idTokenHint = jwtRequest.getIdTokenHint();
        }
        if (StringUtils.isNotBlank(jwtRequest.getLoginHint())) {
            loginHint = jwtRequest.getLoginHint();
        }
        if (StringUtils.isNotBlank(jwtRequest.getBindingMessage())) {
            bindingMessage = jwtRequest.getBindingMessage();
        }
        if (StringUtils.isNotBlank(jwtRequest.getUserCode())) {
            userCodeParam = jwtRequest.getUserCode();
        }
        if (jwtRequest.getRequestedExpiry() != null) {
            requestedExpiry = jwtRequest.getRequestedExpiry();
        } else if (jwtRequest.getExp() != null) {
            requestedExpiry = Math.toIntExact(jwtRequest.getExp() - System.currentTimeMillis() / 1000);
        }
    }
    if (appConfiguration.getFapiCompatibility() && jwtRequest == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    User user = null;
    try {
        if (Strings.isNotBlank(loginHint)) {
            // login_hint
            user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), loginHint);
        } else if (Strings.isNotBlank(idTokenHint)) {
            // id_token_hint
            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
            if (authorizationGrant == null) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            user = authorizationGrant.getUser();
        }
        if (Strings.isNotBlank(loginHintToken)) {
            // login_hint_token
            Jwt jwt = Jwt.parse(loginHintToken);
            SignatureAlgorithm algorithm = jwt.getHeader().getSignatureAlgorithm();
            String keyId = jwt.getHeader().getKeyId();
            if (algorithm == null || Strings.isBlank(keyId)) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            boolean validSignature = false;
            if (algorithm.getFamily() == AlgorithmFamily.RSA) {
                RSAPublicKey publicKey = JwkClient.getRSAPublicKey(client.getJwksUri(), keyId);
                RSASigner rsaSigner = new RSASigner(algorithm, publicKey);
                validSignature = rsaSigner.validate(jwt);
            } else if (algorithm.getFamily() == AlgorithmFamily.EC) {
                ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(client.getJwksUri(), keyId);
                ECDSASigner ecdsaSigner = new ECDSASigner(algorithm, publicKey);
                validSignature = ecdsaSigner.validate(jwt);
            }
            if (!validSignature) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            JSONObject subject = jwt.getClaims().getClaimAsJSON("subject");
            if (subject == null || !subject.has("subject_type") || !subject.has(subject.getString("subject_type"))) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            String subjectTypeKey = subject.getString("subject_type");
            String subjectTypeValue = subject.getString(subjectTypeKey);
            user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), subjectTypeValue);
        }
    } catch (InvalidJwtException e) {
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        log.error(e.getMessage(), e);
    }
    if (user == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
        return builder.build();
    }
    try {
        String userCode = (String) user.getAttribute("oxAuthBackchannelUserCode", true, false);
        DefaultErrorResponse cibaAuthorizeParamsValidation = cibaAuthorizeParamsValidatorService.validateParams(scopes, clientNotificationToken, client.getBackchannelTokenDeliveryMode(), loginHintToken, idTokenHint, loginHint, bindingMessage, client.getBackchannelUserCodeParameter(), userCodeParam, userCode, requestedExpiry);
        if (cibaAuthorizeParamsValidation != null) {
            builder = Response.status(cibaAuthorizeParamsValidation.getStatus());
            builder.entity(errorResponseFactory.errorAsJson(cibaAuthorizeParamsValidation.getType(), cibaAuthorizeParamsValidation.getReason()));
            return builder.build();
        }
        String deviceRegistrationToken = (String) user.getAttribute("oxAuthBackchannelDeviceRegistrationToken", true, false);
        if (deviceRegistrationToken == null) {
            // 401
            builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
            builder.entity(errorResponseFactory.getErrorAsJson(UNAUTHORIZED_END_USER_DEVICE));
            return builder.build();
        }
        int expiresIn = requestedExpiry != null ? requestedExpiry : appConfiguration.getBackchannelAuthenticationResponseExpiresIn();
        Integer interval = client.getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PUSH ? null : appConfiguration.getBackchannelAuthenticationResponseInterval();
        long currentTime = new Date().getTime();
        CibaRequestCacheControl cibaRequestCacheControl = new CibaRequestCacheControl(user, client, expiresIn, scopes, clientNotificationToken, bindingMessage, currentTime, acrValues);
        cibaRequestService.save(cibaRequestCacheControl, expiresIn);
        String authReqId = cibaRequestCacheControl.getAuthReqId();
        // Notify End-User to obtain Consent/Authorization
        cibaEndUserNotificationService.notifyEndUser(cibaRequestCacheControl.getScopesAsString(), cibaRequestCacheControl.getAcrValues(), authReqId, deviceRegistrationToken);
        builder.entity(getJSONObject(authReqId, expiresIn, interval).toString(4).replace("\\/", "/"));
        builder.type(MediaType.APPLICATION_JSON_TYPE);
        builder.cacheControl(ServerUtil.cacheControl(true, false));
    } catch (JSONException e) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        log.error(e.getMessage(), e);
    } catch (InvalidClaimException e) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(org.gluu.oxauth.model.session.SessionClient) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) ArrayList(java.util.ArrayList) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) InvalidClaimException(org.gluu.oxauth.model.exception.InvalidClaimException) RSAPublicKey(org.gluu.oxauth.model.crypto.signature.RSAPublicKey) RSASigner(org.gluu.oxauth.model.jws.RSASigner) JwtAuthorizationRequest(org.gluu.oxauth.model.authorize.JwtAuthorizationRequest) SessionClient(org.gluu.oxauth.model.session.SessionClient) Client(org.gluu.oxauth.model.registration.Client) JwkClient(org.gluu.oxauth.client.JwkClient) DefaultErrorResponse(org.gluu.oxauth.model.error.DefaultErrorResponse) ECDSAPublicKey(org.gluu.oxauth.model.crypto.signature.ECDSAPublicKey) ECDSASigner(org.gluu.oxauth.model.jws.ECDSASigner) Jwt(org.gluu.oxauth.model.jwt.Jwt) JSONException(org.json.JSONException) Date(java.util.Date) DefaultErrorResponse(org.gluu.oxauth.model.error.DefaultErrorResponse) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONObject(org.json.JSONObject)

Example 2 with SignatureAlgorithm

use of org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class UmaClient method request.

private static Token request(final String tokenUrl, final String clientKeyStoreFile, final String clientKeyStorePassword, final String clientId, final String keyId, TokenRequest tokenRequest) throws UmaException {
    OxAuthCryptoProvider cryptoProvider;
    try {
        cryptoProvider = new OxAuthCryptoProvider(clientKeyStoreFile, clientKeyStorePassword, null);
    } catch (Exception ex) {
        throw new UmaException("Failed to initialize crypto provider");
    }
    try {
        String tmpKeyId = keyId;
        if (StringHelper.isEmpty(tmpKeyId)) {
            // Get first key
            List<String> aliases = cryptoProvider.getKeys();
            if (aliases.size() > 0) {
                tmpKeyId = aliases.get(0);
            }
        }
        if (StringHelper.isEmpty(tmpKeyId)) {
            throw new UmaException("UMA keyId is empty");
        }
        SignatureAlgorithm algorithm = cryptoProvider.getSignatureAlgorithm(tmpKeyId);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setCryptoProvider(cryptoProvider);
        tokenRequest.setAlgorithm(algorithm);
        tokenRequest.setKeyId(tmpKeyId);
        tokenRequest.setAudience(tokenUrl);
        Token umaPat = UmaClient.request(tokenUrl, tokenRequest);
        return umaPat;
    } catch (Exception ex) {
        throw new UmaException("Failed to obtain valid UMA PAT token", ex);
    }
}
Also used : OxAuthCryptoProvider(org.gluu.oxauth.model.crypto.OxAuthCryptoProvider) UmaException(org.gluu.oxauth.client.uma.exception.UmaException) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) Token(org.gluu.oxauth.model.uma.wrapper.Token) UmaException(org.gluu.oxauth.client.uma.exception.UmaException)

Example 3 with SignatureAlgorithm

use of org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class UserInfoRestWebServiceImpl method requestUserInfo.

private Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
    if (tokenService.isBearerAuthToken(authorization)) {
        accessToken = tokenService.getBearerToken(authorization);
    }
    log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
    try {
        if (!UserInfoParamsValidator.validateParams(accessToken)) {
            return response(400, UserInfoErrorResponseType.INVALID_REQUEST, "access token is not valid.");
        }
        AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
        if (authorizationGrant == null) {
            log.trace("Failed to find authorization grant by access_token: " + accessToken);
            return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
        }
        oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
        final AbstractToken accessTokenObject = authorizationGrant.getAccessToken(accessToken);
        if (accessTokenObject == null || !accessTokenObject.isValid()) {
            log.trace("Invalid access token object, access_token: {}, isNull: {}, isValid: {}", accessToken, accessTokenObject == null, false);
            return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
        }
        if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Grant object has client_credentials grant_type which is not valid.");
        }
        if (appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Both openid and profile scopes are not present.");
        }
        if (!appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString())) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Missed openid scope.");
        }
        oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
        builder.cacheControl(ServerUtil.cacheControlWithNoStoreTransformAndPrivate());
        builder.header("Pragma", "no-cache");
        User currentUser = authorizationGrant.getUser();
        try {
            currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
        } catch (EntryPersistenceException ex) {
            log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
        }
        if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
            KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
            BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
            builder.type("application/jwt");
            builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
        } else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
            SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
            builder.type("application/jwt");
            builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
        } else {
            builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
            builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
        }
        return builder.build();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        // 500
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
    } finally {
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
    }
}
Also used : JsonWebResponse(org.gluu.oxauth.model.token.JsonWebResponse) Response(javax.ws.rs.core.Response) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException) BlockEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm)

Example 4 with SignatureAlgorithm

use of org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class UmaRptService method createRptJwt.

private String createRptJwt(ExecutionContext executionContext, List<UmaPermission> permissions, Date creationDate, Date expirationDate) throws Exception {
    Client client = executionContext.getClient();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
    if (client.getAccessTokenSigningAlg() != null && SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg()) != null) {
        signatureAlgorithm = SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg());
    }
    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
    final Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setClaim("client_id", client.getClientId());
    jwt.getClaims().setExpirationTime(expirationDate);
    jwt.getClaims().setIssuedAt(creationDate);
    Audience.setAudience(jwt.getClaims(), client);
    if (permissions != null && !permissions.isEmpty()) {
        String pctCode = permissions.iterator().next().getAttributes().get(UmaPermission.PCT);
        if (StringHelper.isNotEmpty(pctCode)) {
            UmaPCT pct = pctService.getByCode(pctCode);
            if (pct != null) {
                jwt.getClaims().setClaim("pct_claims", pct.getClaims().toJsonObject());
            } else {
                log.error("Failed to find PCT with code: " + pctCode + " which is taken from permission object: " + permissions.iterator().next().getDn());
            }
        }
        jwt.getClaims().setClaim("permissions", buildPermissionsJSONObject(permissions));
    }
    runScriptAndInjectValuesIntoJwt(jwt, executionContext);
    return jwtSigner.sign().toString();
}
Also used : JwtSigner(org.gluu.oxauth.model.token.JwtSigner) UmaPCT(org.gluu.oxauth.uma.authorization.UmaPCT) Jwt(org.gluu.oxauth.model.jwt.Jwt) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) Client(org.gluu.oxauth.model.registration.Client)

Example 5 with SignatureAlgorithm

use of org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class OxAuthCryptoProvider method generateKey.

@Override
public JSONObject generateKey(Algorithm algorithm, Long expirationTime, Use use, int keyLength) throws Exception {
    KeyPairGenerator keyGen = null;
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm.getParamName());
    if (signatureAlgorithm == null) {
        signatureAlgorithm = SignatureAlgorithm.RS256;
    }
    if (algorithm == null) {
        throw new RuntimeException("The signature algorithm parameter cannot be null");
    } else if (AlgorithmFamily.RSA.equals(algorithm.getFamily())) {
        keyGen = KeyPairGenerator.getInstance(algorithm.getFamily().toString(), "BC");
        keyGen.initialize(keyLength, new SecureRandom());
    } else if (AlgorithmFamily.EC.equals(algorithm.getFamily())) {
        ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias());
        keyGen = KeyPairGenerator.getInstance(algorithm.getFamily().toString(), "BC");
        keyGen.initialize(eccgen, new SecureRandom());
    } else {
        throw new RuntimeException("The provided signature algorithm parameter is not supported");
    }
    // Generate the key
    KeyPair keyPair = keyGen.generateKeyPair();
    java.security.PrivateKey pk = keyPair.getPrivate();
    // Java API requires a certificate chain
    X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(), expirationTime);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = cert;
    String alias = UUID.randomUUID().toString() + getKidSuffix(use, algorithm);
    keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain);
    final String oldAliasByAlgorithm = getAliasByAlgorithmForDeletion(algorithm, alias, use);
    if (StringUtils.isNotBlank(oldAliasByAlgorithm)) {
        keyStore.deleteEntry(oldAliasByAlgorithm);
        LOG.trace("New key: " + alias + ", deleted key: " + oldAliasByAlgorithm);
    }
    FileOutputStream stream = new FileOutputStream(keyStoreFile);
    keyStore.store(stream, keyStoreSecret.toCharArray());
    PublicKey publicKey = keyPair.getPublic();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(KEY_TYPE, algorithm.getFamily());
    jsonObject.put(KEY_ID, alias);
    jsonObject.put(KEY_USE, use.getParamName());
    jsonObject.put(ALGORITHM, algorithm.getParamName());
    jsonObject.put(EXPIRATION_TIME, expirationTime);
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus()));
        jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent()));
    } else if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        jsonObject.put(CURVE, signatureAlgorithm.getCurve().getName());
        jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX()));
        jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY()));
    }
    JSONArray x5c = new JSONArray();
    x5c.put(Base64.encodeBase64String(cert.getEncoded()));
    jsonObject.put(CERTIFICATE_CHAIN, x5c);
    return jsonObject;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) JSONArray(org.json.JSONArray) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) X509Certificate(java.security.cert.X509Certificate) java.security(java.security) JSONObject(org.json.JSONObject) RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) PrivateKey(java.security.PrivateKey) FileOutputStream(java.io.FileOutputStream)

Aggregations

SignatureAlgorithm (org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm)11 Jwt (org.gluu.oxauth.model.jwt.Jwt)5 JSONObject (org.json.JSONObject)5 InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)4 Client (org.gluu.oxauth.model.registration.Client)4 JwtSigner (org.gluu.oxauth.model.token.JwtSigner)3 JSONException (org.json.JSONException)3 PrivateKey (java.security.PrivateKey)2 X509Certificate (java.security.cert.X509Certificate)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 Response (javax.ws.rs.core.Response)2 OAuth2AuditLog (org.gluu.oxauth.model.audit.OAuth2AuditLog)2 BlockEncryptionAlgorithm (org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm)2 KeyEncryptionAlgorithm (org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm)2 InvalidJweException (org.gluu.oxauth.model.exception.InvalidJweException)2 ClientService (org.gluu.oxauth.service.ClientService)2 RSAKey (com.nimbusds.jose.jwk.RSAKey)1 FileOutputStream (java.io.FileOutputStream)1