Search in sources :

Example 36 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class AuthorizationGrant method createAccessTokenAsJwt.

private String createAccessTokenAsJwt(AccessToken accessToken, ExecutionContext context) throws Exception {
    final User user = getUser();
    final Client client = 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("scope", Lists.newArrayList(getScopes()));
    jwt.getClaims().setClaim("client_id", getClientId());
    jwt.getClaims().setClaim("username", user != null ? user.getAttribute("displayName") : null);
    jwt.getClaims().setClaim("token_type", accessToken.getTokenType().getName());
    // guarantee uniqueness : without it we can get race condition
    jwt.getClaims().setClaim("code", accessToken.getCode());
    jwt.getClaims().setExpirationTime(accessToken.getExpirationDate());
    jwt.getClaims().setIssuedAt(accessToken.getCreationDate());
    jwt.getClaims().setSubjectIdentifier(getSub());
    jwt.getClaims().setClaim("x5t#S256", accessToken.getX5ts256());
    Audience.setAudience(jwt.getClaims(), getClient());
    if (client.getAttributes().getRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims()) {
        runIntrospectionScriptAndInjectValuesIntoJwt(jwt, context);
    }
    final String accessTokenCode = jwtSigner.sign().toString();
    if (log.isTraceEnabled())
        log.trace("Created access token JWT: {}", accessTokenCode + ", claims: " + jwt.getClaims().toJsonString());
    return accessTokenCode;
}
Also used : JwtSigner(org.gluu.oxauth.model.token.JwtSigner) Jwt(org.gluu.oxauth.model.jwt.Jwt) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) Client(org.gluu.oxauth.model.registration.Client)

Example 37 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class RegisterRestWebServiceImpl method registerClientImpl.

private Response registerClientImpl(String requestParams, HttpServletRequest httpRequest, SecurityContext securityContext) {
    Response.ResponseBuilder builder = Response.ok();
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_REGISTRATION);
    try {
        final JSONObject requestObject = new JSONObject(requestParams);
        final JSONObject softwareStatement = validateSoftwareStatement(httpRequest, requestObject);
        if (softwareStatement != null) {
            log.trace("Override request parameters by software_statement");
            for (String key : softwareStatement.keySet()) {
                requestObject.putOpt(key, softwareStatement.get(key));
            }
        }
        final RegisterRequest r = RegisterRequest.fromJson(requestObject, appConfiguration.getLegacyDynamicRegistrationScopeParam());
        if (requestObject.has(SOFTWARE_STATEMENT.toString())) {
            r.setSoftwareStatement(requestObject.getString(SOFTWARE_STATEMENT.toString()));
        }
        log.info("Attempting to register client: applicationType = {}, clientName = {}, redirectUris = {}, isSecure = {}, sectorIdentifierUri = {}, defaultAcrValues = {}", r.getApplicationType(), r.getClientName(), r.getRedirectUris(), securityContext.isSecure(), r.getSectorIdentifierUri(), r.getDefaultAcrValues());
        log.trace("Registration request = {}", requestParams);
        if (!appConfiguration.getDynamicRegistrationEnabled()) {
            log.info("Dynamic client registration is disabled.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Dynamic client registration is disabled.");
        }
        if (!appConfiguration.getDynamicRegistrationPasswordGrantTypeEnabled() && registerParamsValidator.checkIfThereIsPasswordGrantType(r.getGrantTypes())) {
            log.info("Password Grant Type is not allowed for Dynamic Client Registration.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Password Grant Type is not allowed for Dynamic Client Registration.");
        }
        if (r.getSubjectType() == null) {
            SubjectType defaultSubjectType = SubjectType.fromString(appConfiguration.getDefaultSubjectType());
            if (defaultSubjectType != null) {
                r.setSubjectType(defaultSubjectType);
            } else if (appConfiguration.getSubjectTypesSupported().contains(SubjectType.PUBLIC.toString())) {
                r.setSubjectType(SubjectType.PUBLIC);
            } else if (appConfiguration.getSubjectTypesSupported().contains(SubjectType.PAIRWISE.toString())) {
                r.setSubjectType(SubjectType.PAIRWISE);
            }
        }
        // Throws a WebApplicationException whether a validation doesn't pass
        registerParamsValidator.validateAlgorithms(r);
        if (r.getIdTokenSignedResponseAlg() == null) {
            r.setIdTokenSignedResponseAlg(SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm()));
        }
        if (r.getAccessTokenSigningAlg() == null) {
            r.setAccessTokenSigningAlg(SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm()));
        }
        if (r.getClaimsRedirectUris() != null && !r.getClaimsRedirectUris().isEmpty()) {
            if (!registerParamsValidator.validateRedirectUris(r.getGrantTypes(), r.getResponseTypes(), r.getApplicationType(), r.getSubjectType(), r.getClaimsRedirectUris(), r.getSectorIdentifierUri())) {
                log.debug("Value of one or more claims_redirect_uris is invalid, claims_redirect_uris: " + r.getClaimsRedirectUris());
                throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLAIMS_REDIRECT_URI, "Value of one or more claims_redirect_uris is invalid");
            }
        }
        if (!Strings.isNullOrEmpty(r.getInitiateLoginUri())) {
            if (!registerParamsValidator.validateInitiateLoginUri(r.getInitiateLoginUri())) {
                log.debug("The Initiate Login Uri is invalid. The initiate_login_uri must use the https schema: " + r.getInitiateLoginUri());
                throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLAIMS_REDIRECT_URI, "The Initiate Login Uri is invalid. The initiate_login_uri must use the https schema.");
            }
        }
        final Pair<Boolean, String> validateResult = registerParamsValidator.validateParamsClientRegister(r.getApplicationType(), r.getSubjectType(), r.getGrantTypes(), r.getResponseTypes(), r.getRedirectUris());
        if (!validateResult.getFirst()) {
            log.trace("Client parameters are invalid, returns invalid_request error. Reason: " + validateResult.getSecond());
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, validateResult.getSecond());
        }
        if (!registerParamsValidator.validateRedirectUris(r.getGrantTypes(), r.getResponseTypes(), r.getApplicationType(), r.getSubjectType(), r.getRedirectUris(), r.getSectorIdentifierUri())) {
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_REDIRECT_URI, "Failed to validate redirect uris.");
        }
        if (!cibaRegisterParamsValidatorService.validateParams(r.getBackchannelTokenDeliveryMode(), r.getBackchannelClientNotificationEndpoint(), r.getBackchannelAuthenticationRequestSigningAlg(), r.getBackchannelUserCodeParameter(), r.getGrantTypes(), r.getSubjectType(), r.getSectorIdentifierUri(), r.getJwks(), r.getJwksUri())) {
            // CIBA
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Invalid Client Metadata registering to use CIBA (Client Initiated Backchannel Authentication).");
        }
        registerParamsValidator.validateLogoutUri(r.getFrontChannelLogoutUris(), r.getRedirectUris(), errorResponseFactory);
        registerParamsValidator.validateLogoutUri(r.getBackchannelLogoutUris(), r.getRedirectUris(), errorResponseFactory);
        String clientsBaseDN = staticConfiguration.getBaseDn().getClients();
        String inum = inumService.generateClientInum();
        String generatedClientSecret = UUID.randomUUID().toString();
        final Client client = new Client();
        client.setDn("inum=" + inum + "," + clientsBaseDN);
        client.setClientId(inum);
        client.setDeletable(true);
        client.setClientSecret(clientService.encryptSecret(generatedClientSecret));
        client.setRegistrationAccessToken(HandleTokenFactory.generateHandleToken());
        client.setIdTokenTokenBindingCnf(r.getIdTokenTokenBindingCnf());
        final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        client.setClientIdIssuedAt(calendar.getTime());
        if (appConfiguration.getDynamicRegistrationExpirationTime() > 0) {
            // #883 : expiration can be -1, mean does not expire
            calendar.add(Calendar.SECOND, appConfiguration.getDynamicRegistrationExpirationTime());
            client.setClientSecretExpiresAt(calendar.getTime());
            client.setExpirationDate(calendar.getTime());
            client.setTtl(appConfiguration.getDynamicRegistrationExpirationTime());
        }
        client.setDeletable(client.getClientSecretExpiresAt() != null);
        if (StringUtils.isBlank(r.getClientName()) && r.getRedirectUris() != null && !r.getRedirectUris().isEmpty()) {
            try {
                URI redUri = new URI(r.getRedirectUris().get(0));
                client.setClientName(redUri.getHost());
            } catch (Exception e) {
                // ignore
                log.error(e.getMessage(), e);
                client.setClientName("Unknown");
            }
        }
        updateClientFromRequestObject(client, r, false);
        boolean registerClient = true;
        if (externalDynamicClientRegistrationService.isEnabled()) {
            registerClient = externalDynamicClientRegistrationService.executeExternalCreateClientMethods(r, client);
        }
        if (!registerClient) {
            log.trace("Client parameters are invalid, returns invalid_request error. External registration script returned false.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "External registration script returned false.");
        }
        Date currentTime = Calendar.getInstance().getTime();
        client.setLastAccessTime(currentTime);
        client.setLastLogonTime(currentTime);
        Boolean persistClientAuthorizations = appConfiguration.getDynamicRegistrationPersistClientAuthorizations();
        client.setPersistClientAuthorizations(persistClientAuthorizations != null ? persistClientAuthorizations : false);
        clientService.persist(client);
        JSONObject jsonObject = getJSONObject(client);
        builder.entity(jsonObject.toString(4).replace("\\/", "/"));
        log.info("Client registered: clientId = {}, applicationType = {}, clientName = {}, redirectUris = {}, sectorIdentifierUri = {}", client.getClientId(), client.getApplicationType(), client.getClientName(), client.getRedirectUris(), client.getSectorIdentifierUri());
        oAuth2AuditLog.setClientId(client.getClientId());
        oAuth2AuditLog.setScope(clientScopesToString(client));
        oAuth2AuditLog.setSuccess(true);
    } catch (StringEncrypter.EncryptionException e) {
        builder = internalErrorResponse("Encryption exception occured.");
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        builder = internalErrorResponse("Failed to parse JSON.");
        log.error(e.getMessage(), e);
    } catch (WebApplicationException e) {
        log.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        builder = internalErrorResponse("Unknown.");
        log.error(e.getMessage(), e);
    }
    builder.cacheControl(ServerUtil.cacheControl(true, false));
    builder.header("Pragma", "no-cache");
    builder.type(MediaType.APPLICATION_JSON_TYPE);
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : RegisterRequest(org.gluu.oxauth.client.RegisterRequest) WebApplicationException(javax.ws.rs.WebApplicationException) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) JSONException(org.json.JSONException) URI(java.net.URI) StringEncrypter(org.gluu.util.security.StringEncrypter) JSONException(org.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) Response(javax.ws.rs.core.Response) JSONObject(org.json.JSONObject) Client(org.gluu.oxauth.model.registration.Client)

Example 38 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class RegisterRestWebServiceImpl method requestClientUpdate.

@Override
public Response requestClientUpdate(String requestParams, String clientId, @HeaderParam("Authorization") String authorization, @Context HttpServletRequest httpRequest, @Context SecurityContext securityContext) {
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_UPDATE);
    oAuth2AuditLog.setClientId(clientId);
    try {
        log.debug("Attempting to UPDATE client, client_id: {}, requestParams = {}, isSecure = {}", clientId, requestParams, securityContext.isSecure());
        final String accessToken = tokenService.getToken(authorization);
        if (StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(requestParams)) {
            JSONObject requestObject = new JSONObject(requestParams);
            final JSONObject softwareStatement = validateSoftwareStatement(httpRequest, requestObject);
            if (softwareStatement != null) {
                log.trace("Override request parameters by software_statement");
                for (String key : softwareStatement.keySet()) {
                    requestObject.putOpt(key, softwareStatement.get(key));
                }
            }
            final RegisterRequest request = RegisterRequest.fromJson(requestObject, appConfiguration.getLegacyDynamicRegistrationScopeParam());
            if (request != null) {
                boolean redirectUrisValidated = true;
                if (request.getRedirectUris() != null && !request.getRedirectUris().isEmpty()) {
                    redirectUrisValidated = registerParamsValidator.validateRedirectUris(request.getGrantTypes(), request.getResponseTypes(), request.getApplicationType(), request.getSubjectType(), request.getRedirectUris(), request.getSectorIdentifierUri());
                }
                if (redirectUrisValidated) {
                    if (!cibaRegisterParamsValidatorService.validateParams(request.getBackchannelTokenDeliveryMode(), request.getBackchannelClientNotificationEndpoint(), request.getBackchannelAuthenticationRequestSigningAlg(), request.getBackchannelUserCodeParameter(), request.getGrantTypes(), request.getSubjectType(), request.getSectorIdentifierUri(), request.getJwks(), request.getJwksUri())) {
                        return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Invalid Client Metadata registering to use CIBA.")).build();
                    }
                    if (request.getSubjectType() != null && !appConfiguration.getSubjectTypesSupported().contains(request.getSubjectType().toString())) {
                        log.debug("Client UPDATE : parameter subject_type is invalid. Returns BAD_REQUEST response.");
                        applicationAuditLogger.sendMessage(oAuth2AuditLog);
                        return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, "subject_type is invalid.")).build();
                    }
                    final Client client = clientService.getClient(clientId, accessToken);
                    if (client != null) {
                        updateClientFromRequestObject(client, request, true);
                        boolean updateClient = true;
                        if (externalDynamicClientRegistrationService.isEnabled()) {
                            updateClient = externalDynamicClientRegistrationService.executeExternalUpdateClientMethods(request, client);
                        }
                        if (updateClient) {
                            clientService.merge(client);
                            oAuth2AuditLog.setScope(clientScopesToString(client));
                            oAuth2AuditLog.setSuccess(true);
                            applicationAuditLogger.sendMessage(oAuth2AuditLog);
                            return Response.status(Response.Status.OK).entity(clientAsEntity(client)).build();
                        } else {
                            log.trace("The Access Token is not valid for the Client ID, returns invalid_token error.");
                            applicationAuditLogger.sendMessage(oAuth2AuditLog);
                            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_TOKEN, "External registration script returned false.")).build();
                        }
                    } else {
                        log.trace("The Access Token is not valid for the Client ID, returns invalid_token error.");
                        applicationAuditLogger.sendMessage(oAuth2AuditLog);
                        return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_TOKEN, "The Access Token is not valid for the Client ID.")).build();
                    }
                }
            }
        }
        log.debug("Client UPDATE : parameters are invalid. Returns BAD_REQUEST response.");
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
        return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Unknown.")).build();
    } catch (WebApplicationException e) {
        log.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return internalErrorResponse("Unknown.").build();
}
Also used : RegisterRequest(org.gluu.oxauth.client.RegisterRequest) JSONObject(org.json.JSONObject) WebApplicationException(javax.ws.rs.WebApplicationException) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) Client(org.gluu.oxauth.model.registration.Client) JSONException(org.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException)

Example 39 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class AuthorizeService method permissionGranted.

public void permissionGranted(HttpServletRequest httpRequest, final SessionId session) {
    log.trace("permissionGranted");
    try {
        final User user = sessionIdService.getUser(session);
        if (user == null) {
            log.debug("Permission denied. Failed to find session user: userDn = " + session.getUserDn() + ".");
            permissionDenied(session);
            return;
        }
        String clientId = session.getSessionAttributes().get(AuthorizeRequestParam.CLIENT_ID);
        final Client client = clientService.getClient(clientId);
        String scope = session.getSessionAttributes().get(AuthorizeRequestParam.SCOPE);
        String responseType = session.getSessionAttributes().get(AuthorizeRequestParam.RESPONSE_TYPE);
        boolean persistDuringImplicitFlow = ServerUtil.isFalse(appConfiguration.getUseCacheForAllImplicitFlowObjects()) || !ResponseType.isImplicitFlow(responseType);
        if (!client.getTrustedClient() && persistDuringImplicitFlow && client.getPersistClientAuthorizations()) {
            final Set<String> scopes = Sets.newHashSet(org.gluu.oxauth.model.util.StringUtils.spaceSeparatedToList(scope));
            clientAuthorizationsService.add(user.getAttribute("inum"), client.getClientId(), scopes);
        }
        session.addPermission(clientId, true);
        sessionIdService.updateSessionId(session);
        identity.setSessionId(session);
        // OXAUTH-297 - set session_id cookie
        if (!appConfiguration.getInvalidateSessionCookiesAfterAuthorizationFlow()) {
            cookieService.createSessionIdCookie(session, false);
        }
        Map<String, String> sessionAttribute = requestParameterService.getAllowedParameters(session.getSessionAttributes());
        if (sessionAttribute.containsKey(AuthorizeRequestParam.PROMPT)) {
            List<Prompt> prompts = Prompt.fromString(sessionAttribute.get(AuthorizeRequestParam.PROMPT), " ");
            prompts.remove(Prompt.CONSENT);
            sessionAttribute.put(AuthorizeRequestParam.PROMPT, org.gluu.oxauth.model.util.StringUtils.implodeEnum(prompts, " "));
        }
        final String parametersAsString = requestParameterService.parametersAsString(sessionAttribute);
        String uri = httpRequest.getContextPath() + "/restv1/authorize?" + parametersAsString;
        log.trace("permissionGranted, redirectTo: {}", uri);
        if (invalidateSessionCookiesIfNeeded()) {
            if (!uri.contains(AuthorizeRequestParam.SESSION_ID) && appConfiguration.getSessionIdRequestParameterEnabled()) {
                uri += "&session_id=" + session.getId();
            }
        }
        facesService.redirectToExternalURL(uri);
    } catch (UnsupportedEncodingException e) {
        log.trace(e.getMessage(), e);
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) Client(org.gluu.oxauth.model.registration.Client)

Example 40 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class IdTokenFactory method createJwr.

public JsonWebResponse createJwr(IAuthorizationGrant grant, String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, RefreshToken refreshToken, String state, Set<String> scopes, boolean includeIdTokenClaims, Function<JsonWebResponse, Void> preProcessing, Function<JsonWebResponse, Void> postProcessing) throws Exception {
    final Client client = grant.getClient();
    JsonWebResponse jwr = jwrService.createJwr(client);
    fillClaims(jwr, grant, nonce, authorizationCode, accessToken, refreshToken, state, scopes, includeIdTokenClaims, preProcessing, postProcessing);
    if (log.isTraceEnabled())
        log.trace("Created claims for id_token, claims: " + jwr.getClaims().toJsonString());
    return jwrService.encode(jwr, client);
}
Also used : Client(org.gluu.oxauth.model.registration.Client)

Aggregations

Client (org.gluu.oxauth.model.registration.Client)55 WebApplicationException (javax.ws.rs.WebApplicationException)15 Test (org.testng.annotations.Test)14 BaseComponentTest (org.gluu.oxauth.BaseComponentTest)12 InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)10 OAuth2AuditLog (org.gluu.oxauth.model.audit.OAuth2AuditLog)8 JSONException (org.json.JSONException)8 Response (javax.ws.rs.core.Response)6 EntryPersistenceException (org.gluu.persist.exception.EntryPersistenceException)6 JSONObject (org.json.JSONObject)6 IOException (java.io.IOException)5 Date (java.util.Date)5 Jwt (org.gluu.oxauth.model.jwt.Jwt)5 SessionClient (org.gluu.oxauth.model.session.SessionClient)5 URI (java.net.URI)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 JwtAuthorizationRequest (org.gluu.oxauth.model.authorize.JwtAuthorizationRequest)4 ArrayList (java.util.ArrayList)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 Claim (org.gluu.oxauth.model.authorize.Claim)3