Search in sources :

Example 1 with ExternalUpdateTokenContext

use of org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext in project oxAuth by GluuFederation.

the class AuthorizeRestWebServiceImpl method requestAuthorization.

private Response requestAuthorization(String scope, String responseType, String clientId, String redirectUri, String state, String respMode, String nonce, String display, String prompt, Integer maxAge, String uiLocalesStr, String idTokenHint, String loginHint, String acrValuesStr, String amrValuesStr, String request, String requestUri, String requestSessionId, String sessionId, String method, String originHeaders, String codeChallenge, String codeChallengeMethod, String customRespHeaders, String claims, String authReqId, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    // it may be encoded in uma case
    scope = ServerUtil.urlDecode(scope);
    String tokenBindingHeader = httpRequest.getHeader("Sec-Token-Binding");
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.USER_AUTHORIZATION);
    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 authorization: " + "responseType = {}, clientId = {}, scope = {}, redirectUri = {}, nonce = {}, " + "state = {}, request = {}, isSecure = {}, requestSessionId = {}, sessionId = {}", responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(), requestSessionId, sessionId);
    log.debug("Attempting to request authorization: " + "acrValues = {}, amrValues = {}, originHeaders = {}, codeChallenge = {}, codeChallengeMethod = {}, " + "customRespHeaders = {}, claims = {}, tokenBindingHeader = {}", acrValuesStr, amrValuesStr, originHeaders, codeChallenge, codeChallengeMethod, customRespHeaders, claims, tokenBindingHeader);
    ResponseBuilder builder = Response.ok();
    List<String> uiLocales = Util.splittedStringAsList(uiLocalesStr, " ");
    List<ResponseType> responseTypes = ResponseType.fromString(responseType, " ");
    List<Prompt> prompts = Prompt.fromString(prompt, " ");
    List<String> acrValues = Util.splittedStringAsList(acrValuesStr, " ");
    List<String> amrValues = Util.splittedStringAsList(amrValuesStr, " ");
    ResponseMode responseMode = ResponseMode.getByValue(respMode);
    Map<String, String> customParameters = requestParameterService.getCustomParameters(QueryStringDecoder.decode(httpRequest.getQueryString(), true));
    SessionId sessionUser = identity.getSessionId();
    User user = sessionIdService.getUser(sessionUser);
    try {
        Map<String, String> customResponseHeaders = Util.jsonObjectArrayStringAsMap(customRespHeaders);
        updateSessionForROPC(httpRequest, sessionUser);
        Client client = authorizeRestWebServiceValidator.validateClient(clientId, state);
        String deviceAuthzUserCode = deviceAuthorizationService.getUserCodeFromSession(httpRequest);
        redirectUri = authorizeRestWebServiceValidator.validateRedirectUri(client, redirectUri, state, deviceAuthzUserCode, httpRequest);
        log.trace("Validated URI: {}", redirectUri);
        // check after redirect uri is validated
        checkAcrChanged(acrValuesStr, prompts, sessionUser);
        RedirectUriResponse redirectUriResponse = new RedirectUriResponse(new RedirectUri(redirectUri, responseTypes, responseMode), state, httpRequest, errorResponseFactory);
        redirectUriResponse.setFapiCompatible(appConfiguration.getFapiCompatibility());
        Set<String> scopes = scopeChecker.checkScopesPolicy(client, scope);
        JwtAuthorizationRequest jwtRequest = null;
        if (StringUtils.isNotBlank(request) || StringUtils.isNotBlank(requestUri)) {
            try {
                jwtRequest = JwtAuthorizationRequest.createJwtRequest(request, requestUri, client, redirectUriResponse, cryptoProvider, appConfiguration);
                if (jwtRequest == null) {
                    throw createInvalidJwtRequestException(redirectUriResponse, "Failed to parse jwt.");
                }
                if (StringUtils.isNotBlank(jwtRequest.getState())) {
                    state = jwtRequest.getState();
                    redirectUriResponse.setState(state);
                }
                if (appConfiguration.getFapiCompatibility() && StringUtils.isBlank(jwtRequest.getState())) {
                    // #1250 - FAPI : discard state if in JWT we don't have state
                    state = "";
                    redirectUriResponse.setState("");
                }
                authorizeRestWebServiceValidator.validateRequestObject(jwtRequest, redirectUriResponse);
                // MUST be equal
                if (!jwtRequest.getResponseTypes().containsAll(responseTypes) || !responseTypes.containsAll(jwtRequest.getResponseTypes())) {
                    throw createInvalidJwtRequestException(redirectUriResponse, "The responseType parameter is not the same in the JWT");
                }
                if (StringUtils.isBlank(jwtRequest.getClientId()) || !jwtRequest.getClientId().equals(clientId)) {
                    throw createInvalidJwtRequestException(redirectUriResponse, "The clientId parameter is not the same in the JWT");
                }
                // JWT wins
                if (!jwtRequest.getScopes().isEmpty()) {
                    if (!scopes.contains("openid")) {
                        // spec: Even if a scope parameter is present in the Request Object value, a scope parameter MUST always be passed using the OAuth 2.0 request syntax containing the openid scope value
                        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_SCOPE, state, "scope parameter does not contain openid value which is required.")).build());
                    }
                    scopes = scopeChecker.checkScopesPolicy(client, Lists.newArrayList(jwtRequest.getScopes()));
                }
                if (jwtRequest.getRedirectUri() != null && !jwtRequest.getRedirectUri().equals(redirectUri)) {
                    throw createInvalidJwtRequestException(redirectUriResponse, "The redirect_uri parameter is not the same in the JWT");
                }
                if (StringUtils.isNotBlank(jwtRequest.getNonce())) {
                    nonce = jwtRequest.getNonce();
                }
                if (jwtRequest.getDisplay() != null && StringUtils.isNotBlank(jwtRequest.getDisplay().getParamName())) {
                    display = jwtRequest.getDisplay().getParamName();
                }
                if (!jwtRequest.getPrompts().isEmpty()) {
                    prompts = Lists.newArrayList(jwtRequest.getPrompts());
                }
                final IdTokenMember idTokenMember = jwtRequest.getIdTokenMember();
                if (idTokenMember != null) {
                    if (idTokenMember.getMaxAge() != null) {
                        maxAge = idTokenMember.getMaxAge();
                    }
                    final Claim acrClaim = idTokenMember.getClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE);
                    if (acrClaim != null && acrClaim.getClaimValue() != null) {
                        acrValuesStr = acrClaim.getClaimValue().getValueAsString();
                        acrValues = Util.splittedStringAsList(acrValuesStr, " ");
                    }
                    Claim userIdClaim = idTokenMember.getClaim(JwtClaimName.SUBJECT_IDENTIFIER);
                    if (userIdClaim != null && userIdClaim.getClaimValue() != null && userIdClaim.getClaimValue().getValue() != null) {
                        String userIdClaimValue = userIdClaim.getClaimValue().getValue();
                        if (user != null) {
                            String userId = user.getUserId();
                            if (!userId.equalsIgnoreCase(userIdClaimValue)) {
                                builder = redirectUriResponse.createErrorBuilder(AuthorizeErrorResponseType.USER_MISMATCHED);
                                applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                return builder.build();
                            }
                        }
                    }
                }
                requestParameterService.getCustomParameters(jwtRequest, customParameters);
            } catch (WebApplicationException e) {
                throw e;
            } catch (Exception e) {
                log.error("Invalid JWT authorization request. Message : " + e.getMessage(), e);
                throw createInvalidJwtRequestException(redirectUriResponse, "Invalid JWT authorization request");
            }
        }
        if (!cibaRequestService.hasCibaCompatibility(client)) {
            if (appConfiguration.getFapiCompatibility() && jwtRequest == null) {
                throw redirectUriResponse.createWebException(AuthorizeErrorResponseType.INVALID_REQUEST);
            }
            authorizeRestWebServiceValidator.validateRequestJwt(request, requestUri, redirectUriResponse);
        }
        authorizeRestWebServiceValidator.validate(responseTypes, prompts, nonce, state, redirectUri, httpRequest, client, responseMode);
        if (CollectionUtils.isEmpty(acrValues) && !ArrayUtils.isEmpty(client.getDefaultAcrValues())) {
            acrValues = Lists.newArrayList(client.getDefaultAcrValues());
        }
        if (scopes.contains(ScopeConstants.OFFLINE_ACCESS) && !client.getTrustedClient()) {
            if (!responseTypes.contains(ResponseType.CODE)) {
                log.trace("Removed (ignored) offline_scope. Can't find `code` in response_type which is required.");
                scopes.remove(ScopeConstants.OFFLINE_ACCESS);
            }
            if (scopes.contains(ScopeConstants.OFFLINE_ACCESS) && !prompts.contains(Prompt.CONSENT)) {
                log.error("Removed offline_access. Can't find prompt=consent. Consent is required for offline_access.");
                scopes.remove(ScopeConstants.OFFLINE_ACCESS);
            }
        }
        final boolean isResponseTypeValid = AuthorizeParamsValidator.validateResponseTypes(responseTypes, client) && AuthorizeParamsValidator.validateGrantType(responseTypes, client.getGrantTypes(), appConfiguration.getGrantTypesSupported());
        if (!isResponseTypeValid) {
            throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNSUPPORTED_RESPONSE_TYPE, state, "")).build());
        }
        AuthorizationGrant authorizationGrant = null;
        if (user == null) {
            identity.logout();
            if (prompts.contains(Prompt.NONE)) {
                if (authenticationFilterService.isEnabled()) {
                    Map<String, String> params;
                    if (method.equals(HttpMethod.GET)) {
                        params = QueryStringDecoder.decode(httpRequest.getQueryString());
                    } else {
                        params = getGenericRequestMap(httpRequest);
                    }
                    String userDn = authenticationFilterService.processAuthenticationFilters(params);
                    if (userDn != null) {
                        Map<String, String> genericRequestMap = getGenericRequestMap(httpRequest);
                        Map<String, String> parameterMap = Maps.newHashMap(genericRequestMap);
                        Map<String, String> requestParameterMap = requestParameterService.getAllowedParameters(parameterMap);
                        sessionUser = sessionIdService.generateAuthenticatedSessionId(httpRequest, userDn, prompt);
                        sessionUser.setSessionAttributes(requestParameterMap);
                        cookieService.createSessionIdCookie(sessionUser, httpRequest, httpResponse, false);
                        sessionIdService.updateSessionId(sessionUser);
                        user = userService.getUserByDn(sessionUser.getUserDn());
                    } else {
                        builder = redirectUriResponse.createErrorBuilder(AuthorizeErrorResponseType.LOGIN_REQUIRED);
                        applicationAuditLogger.sendMessage(oAuth2AuditLog);
                        return builder.build();
                    }
                } else {
                    builder = redirectUriResponse.createErrorBuilder(AuthorizeErrorResponseType.LOGIN_REQUIRED);
                    applicationAuditLogger.sendMessage(oAuth2AuditLog);
                    return builder.build();
                }
            } else {
                if (prompts.contains(Prompt.LOGIN)) {
                    unauthenticateSession(sessionId, httpRequest);
                    sessionId = null;
                    prompts.remove(Prompt.LOGIN);
                }
                return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
            }
        }
        boolean validAuthenticationMaxAge = authorizeRestWebServiceValidator.validateAuthnMaxAge(maxAge, sessionUser, client);
        if (!validAuthenticationMaxAge) {
            unauthenticateSession(sessionId, httpRequest);
            sessionId = null;
            return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
        }
        oAuth2AuditLog.setUsername(user.getUserId());
        ExternalPostAuthnContext postAuthnContext = new ExternalPostAuthnContext(client, sessionUser, httpRequest, httpResponse);
        final boolean forceReAuthentication = externalPostAuthnService.externalForceReAuthentication(client, postAuthnContext);
        if (forceReAuthentication) {
            unauthenticateSession(sessionId, httpRequest);
            sessionId = null;
            return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
        }
        final boolean forceAuthorization = externalPostAuthnService.externalForceAuthorization(client, postAuthnContext);
        if (forceAuthorization) {
            return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
        }
        ClientAuthorization clientAuthorization = null;
        boolean clientAuthorizationFetched = false;
        if (scopes.size() > 0) {
            if (prompts.contains(Prompt.CONSENT)) {
                return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
            }
            if (client.getTrustedClient()) {
                sessionUser.addPermission(clientId, true);
                sessionIdService.updateSessionId(sessionUser);
            } else {
                clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
                clientAuthorizationFetched = true;
                if (clientAuthorization != null && clientAuthorization.getScopes() != null) {
                    log.trace("ClientAuthorization - scope: " + scope + ", dn: " + clientAuthorization.getDn() + ", requestedScope: " + scopes);
                    if (Arrays.asList(clientAuthorization.getScopes()).containsAll(scopes)) {
                        sessionUser.addPermission(clientId, true);
                        sessionIdService.updateSessionId(sessionUser);
                    } else {
                        return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
                    }
                }
            }
        }
        if (prompts.contains(Prompt.LOGIN)) {
            // workaround for #1030 - remove only authenticated session, for set up acr we set it unauthenticated and then drop in AuthorizeAction
            if (identity.getSessionId().getState() == SessionIdState.AUTHENTICATED) {
                unauthenticateSession(sessionId, httpRequest);
            }
            sessionId = null;
            prompts.remove(Prompt.LOGIN);
            return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
        }
        if (prompts.contains(Prompt.CONSENT) || !sessionUser.isPermissionGrantedForClient(clientId)) {
            if (!clientAuthorizationFetched) {
                clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
            }
            clientAuthorizationsService.clearAuthorizations(clientAuthorization, client.getPersistClientAuthorizations());
            prompts.remove(Prompt.CONSENT);
            return redirectToAuthorizationPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
        }
        if (prompts.contains(Prompt.SELECT_ACCOUNT)) {
            return redirectToSelectAccountPage(redirectUriResponse.getRedirectUri(), responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionId, claims, authReqId, customParameters, oAuth2AuditLog, httpRequest);
        }
        AuthorizationCode authorizationCode = null;
        if (responseTypes.contains(ResponseType.CODE)) {
            authorizationGrant = authorizationGrantList.createAuthorizationCodeGrant(user, client, sessionUser.getAuthenticationTime());
            authorizationGrant.setNonce(nonce);
            authorizationGrant.setJwtAuthorizationRequest(jwtRequest);
            authorizationGrant.setTokenBindingHash(TokenBindingMessage.getTokenBindingIdHashFromTokenBindingMessage(tokenBindingHeader, client.getIdTokenTokenBindingCnf()));
            authorizationGrant.setScopes(scopes);
            authorizationGrant.setCodeChallenge(codeChallenge);
            authorizationGrant.setCodeChallengeMethod(codeChallengeMethod);
            authorizationGrant.setClaims(claims);
            // Store acr_values
            authorizationGrant.setAcrValues(getAcrForGrant(acrValuesStr, sessionUser));
            authorizationGrant.setSessionDn(sessionUser.getDn());
            // call save after object modification!!!
            authorizationGrant.save();
            authorizationCode = authorizationGrant.getAuthorizationCode();
            redirectUriResponse.getRedirectUri().addResponseParameter("code", authorizationCode.getCode());
        }
        AccessToken newAccessToken = null;
        if (responseTypes.contains(ResponseType.TOKEN)) {
            if (authorizationGrant == null) {
                authorizationGrant = authorizationGrantList.createImplicitGrant(user, client, sessionUser.getAuthenticationTime());
                authorizationGrant.setNonce(nonce);
                authorizationGrant.setJwtAuthorizationRequest(jwtRequest);
                authorizationGrant.setScopes(scopes);
                authorizationGrant.setClaims(claims);
                // Store acr_values
                authorizationGrant.setAcrValues(getAcrForGrant(acrValuesStr, sessionUser));
                authorizationGrant.setSessionDn(sessionUser.getDn());
                // call save after object modification!!!
                authorizationGrant.save();
            }
            newAccessToken = authorizationGrant.createAccessToken(httpRequest.getHeader("X-ClientCert"), new ExecutionContext(httpRequest, httpResponse));
            redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.ACCESS_TOKEN, newAccessToken.getCode());
            redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.TOKEN_TYPE, newAccessToken.getTokenType().toString());
            redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.EXPIRES_IN, newAccessToken.getExpiresIn() + "");
        }
        if (responseTypes.contains(ResponseType.ID_TOKEN)) {
            boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
            if (authorizationGrant == null) {
                includeIdTokenClaims = true;
                authorizationGrant = authorizationGrantList.createImplicitGrant(user, client, sessionUser.getAuthenticationTime());
                authorizationGrant.setNonce(nonce);
                authorizationGrant.setJwtAuthorizationRequest(jwtRequest);
                authorizationGrant.setScopes(scopes);
                authorizationGrant.setClaims(claims);
                // Store authentication acr values
                authorizationGrant.setAcrValues(getAcrForGrant(acrValuesStr, sessionUser));
                authorizationGrant.setSessionDn(sessionUser.getDn());
                // call save after object modification, call is asynchronous!!!
                authorizationGrant.save();
            }
            ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(httpRequest, authorizationGrant, client, appConfiguration, attributeService);
            Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
            IdToken idToken = authorizationGrant.createIdToken(nonce, authorizationCode, newAccessToken, null, state, authorizationGrant, includeIdTokenClaims, JwrService.wrapWithSidFunction(TokenBindingMessage.createIdTokenTokingBindingPreprocessing(tokenBindingHeader, client.getIdTokenTokenBindingCnf()), sessionUser.getOutsideSid()), postProcessor);
            redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.ID_TOKEN, idToken.getCode());
        }
        if (authorizationGrant != null && StringHelper.isNotEmpty(acrValuesStr) && !appConfiguration.getFapiCompatibility()) {
            redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.ACR_VALUES, acrValuesStr);
        }
        if (sessionUser.getId() == null) {
            final SessionId newSessionUser = sessionIdService.generateAuthenticatedSessionId(httpRequest, sessionUser.getUserDn(), prompt);
            String newSessionId = newSessionUser.getId();
            sessionUser.setId(newSessionId);
            log.trace("newSessionId = {}", newSessionId);
        }
        if (!appConfiguration.getFapiCompatibility() && appConfiguration.getSessionIdRequestParameterEnabled()) {
            redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.SESSION_ID, sessionUser.getId());
        }
        redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.SID, sessionUser.getOutsideSid());
        redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.SESSION_STATE, sessionIdService.computeSessionState(sessionUser, clientId, redirectUri));
        redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.STATE, state);
        if (scope != null && !scope.isEmpty() && authorizationGrant != null && !appConfiguration.getFapiCompatibility()) {
            scope = authorizationGrant.checkScopesPolicy(scope);
            redirectUriResponse.getRedirectUri().addResponseParameter(AuthorizeResponseParam.SCOPE, scope);
        }
        clientService.updateAccessTime(client, false);
        oAuth2AuditLog.setSuccess(true);
        log.trace("Preparing redirect to: {}", redirectUriResponse.getRedirectUri());
        builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse.getRedirectUri(), httpRequest);
        if (appConfiguration.getCustomHeadersWithAuthorizationResponse()) {
            for (String key : customResponseHeaders.keySet()) {
                builder.header(key, customResponseHeaders.get(key));
            }
        }
        if (StringUtils.isNotBlank(authReqId)) {
            runCiba(authReqId, client, httpRequest, httpResponse);
        }
        if (StringUtils.isNotBlank(deviceAuthzUserCode)) {
            processDeviceAuthorization(deviceAuthzUserCode, user);
        }
    } catch (WebApplicationException e) {
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
        log.error(e.getMessage(), e);
        throw e;
    } catch (AcrChangedException e) {
        // Acr changed
        log.error("ACR is changed, please provide a supported and enabled acr value");
        log.error(e.getMessage(), e);
        RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
        redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.SESSION_SELECTION_REQUIRED, state));
        redirectUriResponse.addResponseParameter("hint", "Use prompt=login in order to alter existing session.");
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
        return RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest).build();
    } catch (EntryPersistenceException e) {
        // Invalid clientId
        builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state, "")).type(MediaType.APPLICATION_JSON_TYPE);
        log.error(e.getMessage(), e);
    } catch (InvalidSessionStateException ex) {
        // Allow to handle it via GlobalExceptionHandler
        throw ex;
    } catch (Exception e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) RedirectUri(org.gluu.oxauth.util.RedirectUri) InvalidSessionStateException(org.gluu.oxauth.model.exception.InvalidSessionStateException) AcrChangedException(org.gluu.oxauth.model.exception.AcrChangedException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Client(org.gluu.oxauth.model.registration.Client) JsonWebResponse(org.gluu.oxauth.model.token.JsonWebResponse) ClientAuthorization(org.gluu.oxauth.model.ldap.ClientAuthorization) ExternalPostAuthnContext(org.gluu.oxauth.service.external.context.ExternalPostAuthnContext) InvalidSessionStateException(org.gluu.oxauth.model.exception.InvalidSessionStateException) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) WebApplicationException(javax.ws.rs.WebApplicationException) AcrChangedException(org.gluu.oxauth.model.exception.AcrChangedException) ExternalUpdateTokenContext(org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext)

Example 2 with ExternalUpdateTokenContext

use of org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext in project oxAuth by GluuFederation.

the class AuthorizeRestWebServiceImpl method runCiba.

private void runCiba(String authReqId, Client client, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    CibaRequestCacheControl cibaRequest = cibaRequestService.getCibaRequest(authReqId);
    if (cibaRequest == null || cibaRequest.getStatus() == CibaRequestStatus.EXPIRED) {
        log.trace("User responded too late and the grant {} has expired, {}", authReqId, cibaRequest);
        return;
    }
    cibaRequestService.removeCibaRequest(authReqId);
    CIBAGrant cibaGrant = authorizationGrantList.createCIBAGrant(cibaRequest);
    RefreshToken refreshToken = cibaGrant.createRefreshToken();
    log.debug("Issuing refresh token: {}", refreshToken.getCode());
    AccessToken accessToken = cibaGrant.createAccessToken(httpRequest.getHeader("X-ClientCert"), new ExecutionContext(httpRequest, httpResponse));
    log.debug("Issuing access token: {}", accessToken.getCode());
    ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(httpRequest, cibaGrant, client, appConfiguration, attributeService);
    Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
    IdToken idToken = cibaGrant.createIdToken(null, null, accessToken, refreshToken, null, cibaGrant, false, null, postProcessor);
    cibaGrant.setTokensDelivered(true);
    cibaGrant.save();
    if (cibaRequest.getClient().getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PUSH) {
        cibaPushTokenDeliveryService.pushTokenDelivery(cibaGrant.getAuthReqId(), cibaGrant.getClient().getBackchannelClientNotificationEndpoint(), cibaRequest.getClientNotificationToken(), accessToken.getCode(), refreshToken.getCode(), idToken.getCode(), accessToken.getExpiresIn());
    } else if (cibaGrant.getClient().getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PING) {
        cibaGrant.setTokensDelivered(false);
        cibaGrant.save();
        cibaPingCallbackService.pingCallback(cibaGrant.getAuthReqId(), cibaGrant.getClient().getBackchannelClientNotificationEndpoint(), cibaRequest.getClientNotificationToken());
    } else if (cibaGrant.getClient().getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.POLL) {
        cibaGrant.setTokensDelivered(false);
        cibaGrant.save();
    }
}
Also used : ExternalUpdateTokenContext(org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext) JsonWebResponse(org.gluu.oxauth.model.token.JsonWebResponse)

Example 3 with ExternalUpdateTokenContext

use of org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext in project oxAuth by GluuFederation.

the class TokenRestWebServiceImpl method processDeviceCodeGrantType.

/**
 * Processes token request for device code grant type.
 * @param grantType Grant type used, should be device code.
 * @param client Client in process.
 * @param deviceCode Device code generated in device authn request.
 * @param scope Scope registered in device authn request.
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @param oAuth2AuditLog OAuth2AuditLog
 */
private Response processDeviceCodeGrantType(final GrantType grantType, final Client client, final String deviceCode, String scope, final HttpServletRequest request, final HttpServletResponse response, final OAuth2AuditLog oAuth2AuditLog) {
    if (!TokenParamsValidator.validateGrantType(grantType, client.getGrantTypes(), appConfiguration.getGrantTypesSupported())) {
        return response(error(400, TokenErrorResponseType.INVALID_GRANT, "Grant types are invalid."), oAuth2AuditLog);
    }
    log.debug("Attempting to find authorizationGrant by deviceCode: '{}'", deviceCode);
    final DeviceCodeGrant deviceCodeGrant = authorizationGrantList.getDeviceCodeGrant(deviceCode);
    log.trace("DeviceCodeGrant : '{}'", deviceCodeGrant);
    if (deviceCodeGrant != null) {
        if (!deviceCodeGrant.getClientId().equals(client.getClientId())) {
            throw new WebApplicationException(response(error(400, TokenErrorResponseType.INVALID_GRANT, "The client is not authorized."), oAuth2AuditLog));
        }
        RefreshToken refToken = deviceCodeGrant.createRefreshToken();
        AccessToken accessToken = deviceCodeGrant.createAccessToken(request.getHeader("X-ClientCert"), new ExecutionContext(request, response));
        ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(request, deviceCodeGrant, client, appConfiguration, attributeService);
        Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
        IdToken idToken = deviceCodeGrant.createIdToken(null, null, accessToken, refToken, null, deviceCodeGrant, false, null, postProcessor);
        RefreshToken reToken = null;
        if (isRefreshTokenAllowed(client, scope, deviceCodeGrant)) {
            reToken = refToken;
        }
        if (scope != null && !scope.isEmpty()) {
            scope = deviceCodeGrant.checkScopesPolicy(scope);
        }
        log.info("Device authorization in token endpoint processed and return to the client, device_code: {}", deviceCodeGrant.getDeviceCode());
        oAuth2AuditLog.updateOAuth2AuditLog(deviceCodeGrant, true);
        grantService.removeByCode(deviceCodeGrant.getDeviceCode());
        return Response.ok().entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), reToken, scope, idToken)).build();
    } else {
        final DeviceAuthorizationCacheControl cacheData = deviceAuthorizationService.getDeviceAuthzByDeviceCode(deviceCode);
        log.trace("DeviceAuthorizationCacheControl data : '{}'", cacheData);
        if (cacheData == null) {
            log.debug("The authentication request has expired for deviceCode: '{}'", deviceCode);
            throw new WebApplicationException(response(error(400, TokenErrorResponseType.EXPIRED_TOKEN, "The authentication request has expired."), oAuth2AuditLog));
        }
        if (!cacheData.getClient().getClientId().equals(client.getClientId())) {
            throw new WebApplicationException(response(error(400, TokenErrorResponseType.INVALID_GRANT, "The client is not authorized."), oAuth2AuditLog));
        }
        long currentTime = new Date().getTime();
        Long lastAccess = cacheData.getLastAccessControl();
        if (lastAccess == null) {
            lastAccess = currentTime;
        }
        cacheData.setLastAccessControl(currentTime);
        deviceAuthorizationService.saveInCache(cacheData, true, true);
        if (cacheData.getStatus() == DeviceAuthorizationStatus.PENDING) {
            int intervalSeconds = appConfiguration.getBackchannelAuthenticationResponseInterval();
            long timeFromLastAccess = currentTime - lastAccess;
            if (timeFromLastAccess > intervalSeconds * 1000) {
                log.debug("Access hasn't been granted yet for deviceCode: '{}'", deviceCode);
                throw new WebApplicationException(response(error(400, TokenErrorResponseType.AUTHORIZATION_PENDING, "User hasn't answered yet"), oAuth2AuditLog));
            } else {
                log.debug("Slow down protection deviceCode: '{}'", deviceCode);
                throw new WebApplicationException(response(error(400, TokenErrorResponseType.SLOW_DOWN, "Client is asking too fast the token."), oAuth2AuditLog));
            }
        }
        if (cacheData.getStatus() == DeviceAuthorizationStatus.DENIED) {
            log.debug("The end-user denied the authorization request for deviceCode: '{}'", deviceCode);
            throw new WebApplicationException(response(error(400, TokenErrorResponseType.ACCESS_DENIED, "The end-user denied the authorization request."), oAuth2AuditLog));
        }
        log.debug("The authentication request has expired for deviceCode: '{}'", deviceCode);
        throw new WebApplicationException(response(error(400, TokenErrorResponseType.EXPIRED_TOKEN, "The authentication request has expired"), oAuth2AuditLog));
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) JsonWebResponse(org.gluu.oxauth.model.token.JsonWebResponse) Date(java.util.Date) ExternalUpdateTokenContext(org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext)

Example 4 with ExternalUpdateTokenContext

use of org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext 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 clientId, String clientSecret, String codeVerifier, String ticket, String claimToken, String claimTokenFormat, String pctCode, String rptCode, String authReqId, String deviceCode, HttpServletRequest request, HttpServletResponse response, SecurityContext sec) {
    log.debug("Attempting to request access token: grantType = {}, code = {}, redirectUri = {}, username = {}, refreshToken = {}, " + "clientId = {}, ExtraParams = {}, isSecure = {}, codeVerifier = {}, ticket = {}", grantType, code, redirectUri, username, refreshToken, clientId, request.getParameterMap(), sec.isSecure(), codeVerifier, ticket);
    boolean isUma = StringUtils.isNotBlank(ticket);
    if (isUma) {
        return umaTokenService.requestRpt(grantType, ticket, claimToken, claimTokenFormat, pctCode, rptCode, scope, request, response);
    }
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REQUEST);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setUsername(username);
    oAuth2AuditLog.setScope(scope);
    String tokenBindingHeader = request.getHeader("Sec-Token-Binding");
    // 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)) {
            log.trace("Failed to validate request parameters");
            return response(error(400, TokenErrorResponseType.INVALID_REQUEST, "Failed to validate request parameters"), oAuth2AuditLog);
        }
        GrantType gt = GrantType.fromString(grantType);
        log.debug("Grant type: '{}'", gt);
        SessionClient sessionClient = identity.getSessionClient();
        Client client = null;
        if (sessionClient != null) {
            client = sessionClient.getClient();
            log.debug("Get sessionClient: '{}'", sessionClient);
        }
        if (client == null) {
            return response(error(401, TokenErrorResponseType.INVALID_GRANT, "Unable to find client."), oAuth2AuditLog);
        }
        log.debug("Get client from session: '{}'", client.getClientId());
        if (client.isDisabled()) {
            return response(error(Response.Status.FORBIDDEN.getStatusCode(), TokenErrorResponseType.DISABLED_CLIENT, "Client is disabled."), oAuth2AuditLog);
        }
        final Function<JsonWebResponse, Void> idTokenTokingBindingPreprocessing = TokenBindingMessage.createIdTokenTokingBindingPreprocessing(tokenBindingHeader, // for all except authorization code grant
        client.getIdTokenTokenBindingCnf());
        final SessionId sessionIdObj = sessionIdService.getSessionId(request);
        final Function<JsonWebResponse, Void> idTokenPreProcessing = JwrService.wrapWithSidFunction(idTokenTokingBindingPreprocessing, sessionIdObj != null ? sessionIdObj.getOutsideSid() : null);
        if (gt == GrantType.AUTHORIZATION_CODE) {
            if (!TokenParamsValidator.validateGrantType(gt, client.getGrantTypes(), appConfiguration.getGrantTypesSupported())) {
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "Grant types are invalid."), oAuth2AuditLog);
            }
            log.debug("Attempting to find authorizationCodeGrant by clientId: '{}', code: '{}'", client.getClientId(), code);
            final AuthorizationCodeGrant authorizationCodeGrant = authorizationGrantList.getAuthorizationCodeGrant(code);
            log.trace("AuthorizationCodeGrant : '{}'", authorizationCodeGrant);
            if (authorizationCodeGrant == null) {
                log.debug("AuthorizationCodeGrant is empty by clientId: '{}', code: '{}'", client.getClientId(), code);
                // if authorization code is not found then code was already used or wrong client provided = remove all grants with this auth code
                grantService.removeAllByAuthorizationCode(code);
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "Unable to find grant object for given code."), oAuth2AuditLog);
            }
            if (!client.getClientId().equals(authorizationCodeGrant.getClientId())) {
                log.debug("AuthorizationCodeGrant is found but belongs to another client. Grant's clientId: '{}', code: '{}'", authorizationCodeGrant.getClientId(), code);
                // if authorization code is not found then code was already used or wrong client provided = remove all grants with this auth code
                grantService.removeAllByAuthorizationCode(code);
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "Client mismatch."), oAuth2AuditLog);
            }
            validatePKCE(authorizationCodeGrant, codeVerifier, oAuth2AuditLog);
            authorizationCodeGrant.setIsCachedWithNoPersistence(false);
            authorizationCodeGrant.save();
            RefreshToken reToken = null;
            if (isRefreshTokenAllowed(client, scope, authorizationCodeGrant)) {
                reToken = authorizationCodeGrant.createRefreshToken();
            }
            if (scope != null && !scope.isEmpty()) {
                scope = authorizationCodeGrant.checkScopesPolicy(scope);
            }
            // create token after scopes are checked
            AccessToken accToken = authorizationCodeGrant.createAccessToken(request.getHeader("X-ClientCert"), new ExecutionContext(request, response));
            IdToken idToken = null;
            if (authorizationCodeGrant.getScopes().contains("openid")) {
                String nonce = authorizationCodeGrant.getNonce();
                boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                final String idTokenTokenBindingCnf = client.getIdTokenTokenBindingCnf();
                Function<JsonWebResponse, Void> authorizationCodePreProcessing = jsonWebResponse -> {
                    if (StringUtils.isNotBlank(idTokenTokenBindingCnf) && StringUtils.isNotBlank(authorizationCodeGrant.getTokenBindingHash())) {
                        TokenBindingMessage.setCnfClaim(jsonWebResponse, authorizationCodeGrant.getTokenBindingHash(), idTokenTokenBindingCnf);
                    }
                    return null;
                };
                ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(request, authorizationCodeGrant, client, appConfiguration, attributeService);
                Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
                idToken = authorizationCodeGrant.createIdToken(nonce, authorizationCodeGrant.getAuthorizationCode(), accToken, null, null, authorizationCodeGrant, includeIdTokenClaims, JwrService.wrapWithSidFunction(authorizationCodePreProcessing, sessionIdObj != null ? sessionIdObj.getOutsideSid() : null), postProcessor);
            }
            oAuth2AuditLog.updateOAuth2AuditLog(authorizationCodeGrant, true);
            grantService.removeAuthorizationCode(authorizationCodeGrant.getAuthorizationCode().getCode());
            final String entity = getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, idToken);
            return response(Response.ok().entity(entity), oAuth2AuditLog);
        }
        if (gt == GrantType.REFRESH_TOKEN) {
            if (!TokenParamsValidator.validateGrantType(gt, client.getGrantTypes(), appConfiguration.getGrantTypesSupported())) {
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "grant_type is not present in client."), oAuth2AuditLog);
            }
            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), refreshToken);
            if (authorizationGrant == null) {
                log.trace("Grant object is not found by refresh token.");
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "Unable to find grant object by refresh token or otherwise token type or client does not match."), oAuth2AuditLog);
            }
            final RefreshToken refreshTokenObject = authorizationGrant.getRefreshToken(refreshToken);
            if (refreshTokenObject == null || !refreshTokenObject.isValid()) {
                log.trace("Invalid refresh token.");
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "Unable to find refresh token or otherwise token type or client does not match."), oAuth2AuditLog);
            }
            // 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 = null;
            if (!appConfiguration.getSkipRefreshTokenDuringRefreshing()) {
                if (appConfiguration.getRefreshTokenExtendLifetimeOnRotation()) {
                    // extend lifetime
                    reToken = authorizationGrant.createRefreshToken();
                } else {
                    // do not extend lifetime
                    reToken = authorizationGrant.createRefreshToken(refreshTokenObject.getExpirationDate());
                }
            }
            if (scope != null && !scope.isEmpty()) {
                scope = authorizationGrant.checkScopesPolicy(scope);
            }
            // create token after scopes are checked
            AccessToken accToken = authorizationGrant.createAccessToken(request.getHeader("X-ClientCert"), new ExecutionContext(request, response));
            IdToken idToken = null;
            if (appConfiguration.getOpenidScopeBackwardCompatibility() && authorizationGrant.getScopes().contains("openid")) {
                boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(request, authorizationGrant, client, appConfiguration, attributeService);
                Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
                idToken = authorizationGrant.createIdToken(null, null, accToken, null, null, authorizationGrant, includeIdTokenClaims, idTokenPreProcessing, postProcessor);
            }
            if (reToken != null && refreshToken != null) {
                // remove refresh token after access token and id_token is created.
                grantService.removeByCode(refreshToken);
            }
            builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, idToken));
            oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
        } else if (gt == GrantType.CLIENT_CREDENTIALS) {
            if (!TokenParamsValidator.validateGrantType(gt, client.getGrantTypes(), appConfiguration.getGrantTypesSupported())) {
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "grant_type is not present in client."), oAuth2AuditLog);
            }
            // TODO: fix the user arg
            ClientCredentialsGrant clientCredentialsGrant = authorizationGrantList.createClientCredentialsGrant(new User(), client);
            if (scope != null && !scope.isEmpty()) {
                scope = clientCredentialsGrant.checkScopesPolicy(scope);
            }
            // create token after scopes are checked
            AccessToken accessToken = clientCredentialsGrant.createAccessToken(request.getHeader("X-ClientCert"), new ExecutionContext(request, response));
            IdToken idToken = null;
            if (appConfiguration.getOpenidScopeBackwardCompatibility() && clientCredentialsGrant.getScopes().contains("openid")) {
                boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(request, clientCredentialsGrant, client, appConfiguration, attributeService);
                Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
                idToken = clientCredentialsGrant.createIdToken(null, null, null, null, null, clientCredentialsGrant, includeIdTokenClaims, idTokenPreProcessing, postProcessor);
            }
            oAuth2AuditLog.updateOAuth2AuditLog(clientCredentialsGrant, true);
            builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, scope, idToken));
        } else if (gt == GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS) {
            if (!TokenParamsValidator.validateGrantType(gt, client.getGrantTypes(), appConfiguration.getGrantTypesSupported())) {
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "grant_type is not present in client."), oAuth2AuditLog);
            }
            boolean authenticated = false;
            User user = null;
            if (authenticationFilterService.isEnabled()) {
                String userDn = authenticationFilterService.processAuthenticationFilters(request.getParameterMap());
                if (StringHelper.isNotEmpty(userDn)) {
                    user = userService.getUserByDn(userDn);
                    authenticated = true;
                }
            }
            if (!authenticated) {
                if (externalResourceOwnerPasswordCredentialsService.isEnabled()) {
                    final ExternalResourceOwnerPasswordCredentialsContext context = new ExternalResourceOwnerPasswordCredentialsContext(request, response, appConfiguration, attributeService, userService);
                    context.setUser(user);
                    if (externalResourceOwnerPasswordCredentialsService.executeExternalAuthenticate(context)) {
                        log.trace("RO PC - User is authenticated successfully by external script.");
                        user = context.getUser();
                    }
                } else {
                    try {
                        authenticated = authenticationService.authenticate(username, password);
                        if (authenticated) {
                            user = authenticationService.getAuthenticatedUser();
                        }
                    } catch (AuthenticationException ex) {
                        log.trace("Failed to authenticate user ", new RuntimeException("User name or password is invalid"));
                    }
                }
            }
            if (user != null) {
                ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = authorizationGrantList.createResourceOwnerPasswordCredentialsGrant(user, client);
                SessionId sessionId = identity.getSessionId();
                if (sessionId != null) {
                    resourceOwnerPasswordCredentialsGrant.setAcrValues(OxConstants.SCRIPT_TYPE_INTERNAL_RESERVED_NAME);
                    resourceOwnerPasswordCredentialsGrant.setSessionDn(sessionId.getDn());
                    // call save after object modification!!!
                    resourceOwnerPasswordCredentialsGrant.save();
                    sessionId.getSessionAttributes().put(Constants.AUTHORIZED_GRANT, gt.getValue());
                    boolean updateResult = sessionIdService.updateSessionId(sessionId, false, true, true);
                    if (!updateResult) {
                        log.debug("Failed to update session entry: '{}'", sessionId.getId());
                    }
                }
                RefreshToken reToken = null;
                if (isRefreshTokenAllowed(client, scope, resourceOwnerPasswordCredentialsGrant)) {
                    reToken = resourceOwnerPasswordCredentialsGrant.createRefreshToken();
                }
                if (scope != null && !scope.isEmpty()) {
                    scope = resourceOwnerPasswordCredentialsGrant.checkScopesPolicy(scope);
                }
                // create token after scopes are checked
                AccessToken accessToken = resourceOwnerPasswordCredentialsGrant.createAccessToken(request.getHeader("X-ClientCert"), new ExecutionContext(request, response));
                IdToken idToken = null;
                if (appConfiguration.getOpenidScopeBackwardCompatibility() && resourceOwnerPasswordCredentialsGrant.getScopes().contains("openid")) {
                    boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                    ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(request, resourceOwnerPasswordCredentialsGrant, client, appConfiguration, attributeService);
                    Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
                    idToken = resourceOwnerPasswordCredentialsGrant.createIdToken(null, null, null, null, null, resourceOwnerPasswordCredentialsGrant, includeIdTokenClaims, idTokenPreProcessing, postProcessor);
                }
                oAuth2AuditLog.updateOAuth2AuditLog(resourceOwnerPasswordCredentialsGrant, true);
                builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), reToken, scope, idToken));
            } else {
                log.debug("Invalid user", new RuntimeException("User is empty"));
                builder = error(401, TokenErrorResponseType.INVALID_CLIENT, "Invalid user.");
            }
        } else if (gt == GrantType.CIBA) {
            if (!appConfiguration.getCibaEnabled()) {
                log.warn("Trying to get CIBA token, however CIBA config is disabled.");
                return response(error(400, TokenErrorResponseType.INVALID_REQUEST, "Grant types are invalid."), oAuth2AuditLog);
            }
            if (!TokenParamsValidator.validateGrantType(gt, client.getGrantTypes(), appConfiguration.getGrantTypesSupported())) {
                return response(error(400, TokenErrorResponseType.INVALID_GRANT, "Grant types are invalid."), oAuth2AuditLog);
            }
            log.debug("Attempting to find authorizationGrant by authReqId: '{}'", authReqId);
            final CIBAGrant cibaGrant = authorizationGrantList.getCIBAGrant(authReqId);
            log.trace("AuthorizationGrant : '{}'", cibaGrant);
            if (cibaGrant != null) {
                if (!cibaGrant.getClientId().equals(client.getClientId())) {
                    builder = error(400, TokenErrorResponseType.INVALID_GRANT, "The client is not authorized.");
                    return response(builder, oAuth2AuditLog);
                }
                if (cibaGrant.getClient().getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PING || cibaGrant.getClient().getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.POLL) {
                    if (!cibaGrant.isTokensDelivered()) {
                        RefreshToken refToken = cibaGrant.createRefreshToken();
                        AccessToken accessToken = cibaGrant.createAccessToken(request.getHeader("X-ClientCert"), new ExecutionContext(request, response));
                        ExternalUpdateTokenContext context = new ExternalUpdateTokenContext(request, cibaGrant, client, appConfiguration, attributeService);
                        Function<JsonWebResponse, Void> postProcessor = externalUpdateTokenService.buildModifyIdTokenProcessor(context);
                        IdToken idToken = cibaGrant.createIdToken(null, null, accessToken, refToken, null, cibaGrant, false, null, postProcessor);
                        cibaGrant.setTokensDelivered(true);
                        cibaGrant.save();
                        RefreshToken reToken = null;
                        if (isRefreshTokenAllowed(client, scope, cibaGrant)) {
                            reToken = refToken;
                        }
                        if (scope != null && !scope.isEmpty()) {
                            scope = cibaGrant.checkScopesPolicy(scope);
                        }
                        builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), reToken, scope, idToken));
                        oAuth2AuditLog.updateOAuth2AuditLog(cibaGrant, true);
                    } else {
                        builder = error(400, TokenErrorResponseType.INVALID_GRANT, "AuthReqId is no longer available.");
                    }
                } else {
                    log.debug("Client is not using Poll flow authReqId: '{}'", authReqId);
                    builder = error(400, TokenErrorResponseType.UNAUTHORIZED_CLIENT, "The client is not authorized as it is configured in Push Mode");
                }
            } else {
                final CibaRequestCacheControl cibaRequest = cibaRequestService.getCibaRequest(authReqId);
                log.trace("Ciba request : '{}'", cibaRequest);
                if (cibaRequest != null) {
                    if (!cibaRequest.getClient().getClientId().equals(client.getClientId())) {
                        builder = error(400, TokenErrorResponseType.INVALID_GRANT, "The client is not authorized.");
                        return response(builder, oAuth2AuditLog);
                    }
                    long currentTime = new Date().getTime();
                    Long lastAccess = cibaRequest.getLastAccessControl();
                    if (lastAccess == null) {
                        lastAccess = currentTime;
                    }
                    cibaRequest.setLastAccessControl(currentTime);
                    cibaRequestService.update(cibaRequest);
                    if (cibaRequest.getStatus() == CibaRequestStatus.PENDING) {
                        int intervalSeconds = appConfiguration.getBackchannelAuthenticationResponseInterval();
                        long timeFromLastAccess = currentTime - lastAccess;
                        if (timeFromLastAccess > intervalSeconds * 1000) {
                            log.debug("Access hasn't been granted yet for authReqId: '{}'", authReqId);
                            builder = error(400, TokenErrorResponseType.AUTHORIZATION_PENDING, "User hasn't answered yet");
                        } else {
                            log.debug("Slow down protection authReqId: '{}'", authReqId);
                            builder = error(400, TokenErrorResponseType.SLOW_DOWN, "Client is asking too fast the token.");
                        }
                    } else if (cibaRequest.getStatus() == CibaRequestStatus.DENIED) {
                        log.debug("The end-user denied the authorization request for authReqId: '{}'", authReqId);
                        builder = error(400, TokenErrorResponseType.ACCESS_DENIED, "The end-user denied the authorization request.");
                    } else if (cibaRequest.getStatus() == CibaRequestStatus.EXPIRED) {
                        log.debug("The authentication request has expired for authReqId: '{}'", authReqId);
                        builder = error(400, TokenErrorResponseType.EXPIRED_TOKEN, "The authentication request has expired");
                    }
                } else {
                    log.debug("AuthorizationGrant is empty by authReqId: '{}'", authReqId);
                    builder = error(400, TokenErrorResponseType.EXPIRED_TOKEN, "Unable to find grant object for given auth_req_id.");
                }
            }
        } else if (gt == GrantType.DEVICE_CODE) {
            return processDeviceCodeGrantType(gt, client, deviceCode, scope, request, response, oAuth2AuditLog);
        }
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    }
    return response(builder, oAuth2AuditLog);
}
Also used : TokenParamsValidator(org.gluu.oxauth.model.token.TokenParamsValidator) TokenBindingMessage(org.gluu.oxauth.model.crypto.binding.TokenBindingMessage) StringUtils(org.apache.commons.lang.StringUtils) JwrService(org.gluu.oxauth.model.token.JwrService) Arrays(java.util.Arrays) ApplicationAuditLogger(org.gluu.oxauth.audit.ApplicationAuditLogger) SessionClient(org.gluu.oxauth.model.session.SessionClient) ExternalUpdateTokenContext(org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext) Date(java.util.Date) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) StringHelper(org.gluu.util.StringHelper) Client(org.gluu.oxauth.model.registration.Client) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) OxConstants(org.gluu.util.OxConstants) ExternalUpdateTokenService(org.gluu.oxauth.service.external.ExternalUpdateTokenService) JSONException(org.json.JSONException) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) JSONObject(org.json.JSONObject) ServerUtil(org.gluu.oxauth.util.ServerUtil) org.gluu.oxauth.model.common(org.gluu.oxauth.model.common) AppConfiguration(org.gluu.oxauth.model.configuration.AppConfiguration) JsonWebResponse(org.gluu.oxauth.model.token.JsonWebResponse) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Function(com.google.common.base.Function) Logger(org.slf4j.Logger) Identity(org.gluu.oxauth.security.Identity) HttpServletResponse(javax.servlet.http.HttpServletResponse) Action(org.gluu.oxauth.model.audit.Action) UmaTokenService(org.gluu.oxauth.uma.service.UmaTokenService) AuthenticationException(org.gluu.persist.exception.AuthenticationException) CodeVerifier(org.gluu.oxauth.model.authorize.CodeVerifier) org.gluu.oxauth.service(org.gluu.oxauth.service) Constants(org.gluu.oxauth.model.config.Constants) CibaRequestService(org.gluu.oxauth.service.ciba.CibaRequestService) Response(javax.ws.rs.core.Response) ErrorResponseFactory(org.gluu.oxauth.model.error.ErrorResponseFactory) ExternalResourceOwnerPasswordCredentialsContext(org.gluu.oxauth.service.external.context.ExternalResourceOwnerPasswordCredentialsContext) ExternalResourceOwnerPasswordCredentialsService(org.gluu.oxauth.service.external.ExternalResourceOwnerPasswordCredentialsService) WebApplicationException(javax.ws.rs.WebApplicationException) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) TokenErrorResponseType(org.gluu.oxauth.model.token.TokenErrorResponseType) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(org.gluu.oxauth.model.session.SessionClient) AuthenticationException(org.gluu.persist.exception.AuthenticationException) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) Function(com.google.common.base.Function) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) SessionClient(org.gluu.oxauth.model.session.SessionClient) Client(org.gluu.oxauth.model.registration.Client) JsonWebResponse(org.gluu.oxauth.model.token.JsonWebResponse) ExternalResourceOwnerPasswordCredentialsContext(org.gluu.oxauth.service.external.context.ExternalResourceOwnerPasswordCredentialsContext) Date(java.util.Date) JSONException(org.json.JSONException) AuthenticationException(org.gluu.persist.exception.AuthenticationException) WebApplicationException(javax.ws.rs.WebApplicationException) ExternalUpdateTokenContext(org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext)

Aggregations

JsonWebResponse (org.gluu.oxauth.model.token.JsonWebResponse)4 ExternalUpdateTokenContext (org.gluu.oxauth.service.external.context.ExternalUpdateTokenContext)4 WebApplicationException (javax.ws.rs.WebApplicationException)3 Date (java.util.Date)2 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)2 OAuth2AuditLog (org.gluu.oxauth.model.audit.OAuth2AuditLog)2 Client (org.gluu.oxauth.model.registration.Client)2 Function (com.google.common.base.Function)1 Strings (com.google.common.base.Strings)1 Arrays (java.util.Arrays)1 Inject (javax.inject.Inject)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Path (javax.ws.rs.Path)1 MediaType (javax.ws.rs.core.MediaType)1 Response (javax.ws.rs.core.Response)1 SecurityContext (javax.ws.rs.core.SecurityContext)1 StringUtils (org.apache.commons.lang.StringUtils)1 ApplicationAuditLogger (org.gluu.oxauth.audit.ApplicationAuditLogger)1 Action (org.gluu.oxauth.model.audit.Action)1