Search in sources :

Example 1 with Prompt

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

the class AuthorizeAction method permissionGranted.

public void permissionGranted(SessionState session) {
    try {
        final User user = userService.getUserByDn(session.getUserDn());
        if (user == null) {
            log.error("Permission denied. Failed to find session user: userDn = " + session.getUserDn() + ".");
            permissionDenied();
            return;
        }
        if (clientId == null) {
            clientId = session.getSessionAttributes().get(AuthorizeRequestParam.CLIENT_ID);
        }
        final Client client = clientService.getClient(clientId);
        if (scope == null) {
            scope = session.getSessionAttributes().get(AuthorizeRequestParam.SCOPE);
        }
        // ldap database, and serve no purpose.
        if (client.getPersistClientAuthorizations() && !client.getTrustedClient()) {
            final Set<String> scopes = Sets.newHashSet(org.xdi.oxauth.model.util.StringUtils.spaceSeparatedToList(scope));
            clientAuthorizationsService.add(user.getAttribute("inum"), client.getClientId(), scopes);
        }
        session.addPermission(clientId, true);
        sessionStateService.updateSessionState(session);
        // OXAUTH-297 - set session_state cookie
        sessionStateService.createSessionStateCookie(sessionState);
        Map<String, String> sessionAttribute = authenticationService.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.xdi.oxauth.model.util.StringUtils.implodeEnum(prompts, " "));
        }
        final String parametersAsString = authenticationService.parametersAsString(sessionAttribute);
        final String uri = "seam/resource/restv1/oxauth/authorize?" + parametersAsString;
        log.trace("permissionGranted, redirectTo: {}", uri);
        facesService.redirectToExternalURL(uri);
    } catch (UnsupportedEncodingException e) {
        log.trace(e.getMessage(), e);
    }
}
Also used : User(org.xdi.oxauth.model.common.User) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Prompt(org.xdi.oxauth.model.common.Prompt) Client(org.xdi.oxauth.model.registration.Client)

Example 2 with Prompt

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

the class JwtAuthorizationRequest method payloadToJSONObject.

protected JSONObject payloadToJSONObject() throws JSONException {
    JSONObject obj = new JSONObject();
    try {
        if (responseTypes != null && !responseTypes.isEmpty()) {
            if (responseTypes.size() == 1) {
                ResponseType responseType = responseTypes.get(0);
                obj.put("response_type", responseType);
            } else {
                JSONArray responseTypeJsonArray = new JSONArray();
                for (ResponseType responseType : responseTypes) {
                    responseTypeJsonArray.put(responseType);
                }
                obj.put("response_type", responseTypeJsonArray);
            }
        }
        if (StringUtils.isNotBlank(clientId)) {
            obj.put("client_id", clientId);
        }
        if (scopes != null && !scopes.isEmpty()) {
            if (scopes.size() == 1) {
                String scope = scopes.get(0);
                obj.put("scope", scope);
            } else {
                JSONArray scopeJsonArray = new JSONArray();
                for (String scope : scopes) {
                    scopeJsonArray.put(scope);
                }
                obj.put("scope", scopeJsonArray);
            }
        }
        if (StringUtils.isNotBlank(redirectUri)) {
            obj.put("redirect_uri", URLEncoder.encode(redirectUri, "UTF-8"));
        }
        if (StringUtils.isNotBlank(state)) {
            obj.put("state", state);
        }
        if (StringUtils.isNotBlank(nonce)) {
            obj.put("nonce", nonce);
        }
        if (display != null) {
            obj.put("display", display);
        }
        if (prompts != null && !prompts.isEmpty()) {
            JSONArray promptJsonArray = new JSONArray();
            for (Prompt prompt : prompts) {
                promptJsonArray.put(prompt);
            }
            obj.put("prompt", promptJsonArray);
        }
        if (maxAge != null) {
            obj.put("max_age", maxAge);
        }
        if (uiLocales != null && !uiLocales.isEmpty()) {
            JSONArray uiLocalesJsonArray = new JSONArray(uiLocales);
            obj.put("ui_locales", uiLocalesJsonArray);
        }
        if (claimsLocales != null && !claimsLocales.isEmpty()) {
            JSONArray claimsLocalesJsonArray = new JSONArray(claimsLocales);
            obj.put("claims_locales", claimsLocalesJsonArray);
        }
        if (StringUtils.isNotBlank(idTokenHint)) {
            obj.put("id_token_hint", idTokenHint);
        }
        if (StringUtils.isNotBlank(loginHint)) {
            obj.put("login_hint", loginHint);
        }
        if (acrValues != null && !acrValues.isEmpty()) {
            JSONArray acrValuesJsonArray = new JSONArray(acrValues);
            obj.put("acr_values", acrValues);
        }
        if (StringUtils.isNotBlank(registration)) {
            obj.put("registration", registration);
        }
        if (userInfoMember != null || idTokenMember != null) {
            JSONObject claimsObj = new JSONObject();
            if (userInfoMember != null) {
                claimsObj.put("userinfo", userInfoMember.toJSONObject());
            }
            if (idTokenMember != null) {
                claimsObj.put("id_token", idTokenMember.toJSONObject());
            }
            obj.put("claims", claimsObj);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return obj;
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) JSONArray(org.codehaus.jettison.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Prompt(org.xdi.oxauth.model.common.Prompt) ResponseType(org.xdi.oxauth.model.common.ResponseType)

Example 3 with Prompt

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

the class JwtAuthorizationRequest method loadPayload.

private void loadPayload(String payload) throws JSONException, UnsupportedEncodingException {
    JSONObject jsonPayload = new JSONObject(payload);
    if (jsonPayload.has("response_type")) {
        JSONArray responseTypeJsonArray = jsonPayload.optJSONArray("response_type");
        if (responseTypeJsonArray != null) {
            for (int i = 0; i < responseTypeJsonArray.length(); i++) {
                ResponseType responseType = ResponseType.fromString(responseTypeJsonArray.getString(i));
                responseTypes.add(responseType);
            }
        } else {
            responseTypes.addAll(ResponseType.fromString(jsonPayload.getString("response_type"), " "));
        }
    }
    if (jsonPayload.has("client_id")) {
        clientId = jsonPayload.getString("client_id");
    }
    if (jsonPayload.has("scope")) {
        JSONArray scopesJsonArray = jsonPayload.optJSONArray("scope");
        if (scopesJsonArray != null) {
            for (int i = 0; i < scopesJsonArray.length(); i++) {
                String scope = scopesJsonArray.getString(i);
                scopes.add(scope);
            }
        } else {
            String scopeStringList = jsonPayload.getString("scope");
            scopes.addAll(Util.splittedStringAsList(scopeStringList, " "));
        }
    }
    if (jsonPayload.has("redirect_uri")) {
        redirectUri = URLDecoder.decode(jsonPayload.getString("redirect_uri"), "UTF-8");
    }
    if (jsonPayload.has("nonce")) {
        nonce = jsonPayload.getString("nonce");
    }
    if (jsonPayload.has("state")) {
        state = jsonPayload.getString("state");
    }
    if (jsonPayload.has("display")) {
        display = Display.fromString(jsonPayload.getString("display"));
    }
    if (jsonPayload.has("prompt")) {
        JSONArray promptJsonArray = jsonPayload.optJSONArray("prompt");
        if (promptJsonArray != null) {
            for (int i = 0; i < promptJsonArray.length(); i++) {
                Prompt prompt = Prompt.fromString(promptJsonArray.getString(i));
                prompts.add(prompt);
            }
        } else {
            prompts.addAll(Prompt.fromString(jsonPayload.getString("prompt"), " "));
        }
    }
    if (jsonPayload.has("claims")) {
        JSONObject claimsJsonObject = jsonPayload.getJSONObject("claims");
        if (claimsJsonObject.has("userinfo")) {
            userInfoMember = new UserInfoMember(claimsJsonObject.getJSONObject("userinfo"));
        }
        if (claimsJsonObject.has("id_token")) {
            idTokenMember = new IdTokenMember(claimsJsonObject.getJSONObject("id_token"));
        }
    }
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) JSONArray(org.codehaus.jettison.json.JSONArray) Prompt(org.xdi.oxauth.model.common.Prompt) ResponseType(org.xdi.oxauth.model.common.ResponseType)

Example 4 with Prompt

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

the class AuthorizeRestWebServiceImpl method requestAuthorization.

public 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 requestSessionState, String sessionState, String accessToken, String method, String originHeaders, String codeChallenge, String codeChallengeMethod, String customRespHeaders, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    // it may be encoded in uma case
    scope = ServerUtil.urlDecode(scope);
    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 = {}, requestSessionState = {}, sessionState = {}", responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(), requestSessionState, sessionState);
    log.debug("Attempting to request authorization: " + "acrValues = {}, amrValues = {}, originHeaders = {}, codeChallenge = {}, codeChallengeMethod = {}", acrValuesStr, amrValuesStr, originHeaders, codeChallenge, codeChallengeMethod);
    ResponseBuilder builder = Response.ok();
    List<String> uiLocales = null;
    if (StringUtils.isNotBlank(uiLocalesStr)) {
        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);
    SessionState sessionUser = identity.getSessionState();
    User user = sessionUser != null && StringUtils.isNotBlank(sessionUser.getUserDn()) ? userService.getUserByDn(sessionUser.getUserDn()) : null;
    try {
        Map<String, String> customResponseHeaders = Util.jsonObjectArrayStringAsMap(customRespHeaders);
        sessionStateService.assertAuthenticatedSessionCorrespondsToNewRequest(sessionUser, acrValuesStr);
        if (!AuthorizeParamsValidator.validateParams(responseType, clientId, prompts, nonce, request, requestUri)) {
            if (clientId != null && redirectUri != null && redirectionUriService.validateRedirectionUri(clientId, redirectUri) != null) {
                RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
                redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST, state));
                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
            } else {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, state));
            }
        } else {
            Client client = clientService.getClient(clientId);
            if (CollectionUtils.isEmpty(acrValues) && client != null && !ArrayUtils.isEmpty(client.getDefaultAcrValues())) {
                acrValues = new ArrayList<String>();
                acrValues.addAll(Arrays.asList(client.getDefaultAcrValues()));
            }
            JwtAuthorizationRequest jwtAuthorizationRequest = null;
            if (client != null) {
                List<String> scopes = new ArrayList<String>();
                if (StringHelper.isNotEmpty(scope)) {
                    Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
                    scopes.addAll(grantedScopes);
                }
                // Validate redirectUri
                redirectUri = redirectionUriService.validateRedirectionUri(clientId, redirectUri);
                boolean validRedirectUri = redirectUri != null;
                if (AuthorizeParamsValidator.validateResponseTypes(responseTypes, client)) {
                    if (validRedirectUri) {
                        if (StringUtils.isNotBlank(accessToken)) {
                            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
                            if (authorizationGrant == null) {
                                RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
                                redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.ACCESS_DENIED, state));
                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                return builder.build();
                            } else {
                                oAuth2AuditLog.setUsername(authorizationGrant.getUserId());
                                user = userService.getUser(authorizationGrant.getUserId());
                                sessionUser = sessionStateService.generateAuthenticatedSessionState(user.getDn(), prompt);
                                sessionUser.addPermission(client.getClientId(), true);
                            }
                        }
                        if (StringUtils.isNotBlank(requestUri)) {
                            boolean validRequestUri = false;
                            try {
                                URI reqUri = new URI(requestUri);
                                String reqUriHash = reqUri.getFragment();
                                String reqUriWithoutFragment = reqUri.getScheme() + ":" + reqUri.getSchemeSpecificPart();
                                ClientRequest clientRequest = new ClientRequest(reqUriWithoutFragment);
                                clientRequest.setHttpMethod(HttpMethod.GET);
                                ClientResponse<String> clientResponse = clientRequest.get(String.class);
                                int status = clientResponse.getStatus();
                                if (status == 200) {
                                    request = clientResponse.getEntity(String.class);
                                    if (StringUtils.isBlank(reqUriHash)) {
                                        validRequestUri = true;
                                    } else {
                                        String hash = Base64Util.base64urlencode(JwtUtil.getMessageDigestSHA256(request));
                                        validRequestUri = StringUtils.equals(reqUriHash, hash);
                                    }
                                }
                                if (validRequestUri) {
                                    requestUri = null;
                                } else {
                                    RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
                                    redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST_URI, state));
                                    builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                    applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                    return builder.build();
                                }
                            } catch (URISyntaxException e) {
                                log.error(e.getMessage(), e);
                            } catch (UnknownHostException e) {
                                log.error(e.getMessage(), e);
                            } catch (ConnectException e) {
                                log.error(e.getMessage(), e);
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                            }
                        }
                        boolean invalidOpenidRequestObject = false;
                        if (StringUtils.isNotBlank(request)) {
                            try {
                                jwtAuthorizationRequest = new JwtAuthorizationRequest(appConfiguration, request, client);
                                if (!jwtAuthorizationRequest.getResponseTypes().containsAll(responseTypes) || !responseTypes.containsAll(jwtAuthorizationRequest.getResponseTypes())) {
                                    throw new InvalidJwtException("The responseType parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getClientId() != null && !jwtAuthorizationRequest.getClientId().equals(clientId)) {
                                    throw new InvalidJwtException("The clientId parameter is not the same in the JWT");
                                } else if (!jwtAuthorizationRequest.getScopes().containsAll(scopes) || !scopes.containsAll(jwtAuthorizationRequest.getScopes())) {
                                    throw new InvalidJwtException("The scope parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getRedirectUri() != null && !jwtAuthorizationRequest.getRedirectUri().equals(redirectUri)) {
                                    throw new InvalidJwtException("The redirectUri parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getState() != null && StringUtils.isNotBlank(state) && !jwtAuthorizationRequest.getState().equals(state)) {
                                    throw new InvalidJwtException("The state parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getNonce() != null && StringUtils.isNotBlank(nonce) && !jwtAuthorizationRequest.getNonce().equals(nonce)) {
                                    throw new InvalidJwtException("The nonce parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getDisplay() != null && StringUtils.isNotBlank(display) && !jwtAuthorizationRequest.getDisplay().getParamName().equals(display)) {
                                    throw new InvalidJwtException("The display parameter is not the same in the JWT");
                                } else if (!jwtAuthorizationRequest.getPrompts().isEmpty() && !prompts.isEmpty() && !jwtAuthorizationRequest.getPrompts().containsAll(prompts)) {
                                    throw new InvalidJwtException("The prompt parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null && maxAge != null && !jwtAuthorizationRequest.getIdTokenMember().getMaxAge().equals(maxAge)) {
                                    throw new InvalidJwtException("The maxAge parameter is not the same in the JWT");
                                }
                            } catch (InvalidJwtException e) {
                                invalidOpenidRequestObject = true;
                                log.debug("Invalid JWT authorization request. Exception = {}, Message = {}", e, e.getClass().getName(), e.getMessage());
                            } catch (Exception e) {
                                invalidOpenidRequestObject = true;
                                log.debug("Invalid JWT authorization request. Exception = {}, Message = {}", e, e.getClass().getName(), e.getMessage());
                            }
                        }
                        if (invalidOpenidRequestObject) {
                            RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
                            redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_OPENID_REQUEST_OBJECT, state));
                            builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                        } else {
                            AuthorizationGrant authorizationGrant = null;
                            RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
                            if (jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null) {
                                Claim userIdClaim = jwtAuthorizationRequest.getIdTokenMember().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)) {
                                            redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.USER_MISMATCHED, state));
                                            builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                            applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                            return builder.build();
                                        }
                                    }
                                }
                            }
                            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 = authenticationService.getAllowedParameters(parameterMap);
                                            sessionUser = sessionStateService.generateAuthenticatedSessionState(userDn, prompt);
                                            sessionUser.setSessionAttributes(requestParameterMap);
                                            sessionStateService.createSessionStateCookie(sessionUser.getId(), httpResponse);
                                            sessionStateService.updateSessionState(sessionUser);
                                            user = userService.getUserByDn(sessionUser.getUserDn());
                                        } else {
                                            redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.LOGIN_REQUIRED, state));
                                            builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                            applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                            return builder.build();
                                        }
                                    } else {
                                        redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.LOGIN_REQUIRED, state));
                                        builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                        applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                        return builder.build();
                                    }
                                } else {
                                    if (prompts.contains(Prompt.LOGIN)) {
                                        endSession(sessionState, httpRequest, httpResponse);
                                        sessionState = null;
                                        prompts.remove(Prompt.LOGIN);
                                    }
                                    redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionState);
                                    builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                    applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                    return builder.build();
                                }
                            }
                            oAuth2AuditLog.setUsername(user.getUserId());
                            ClientAuthorizations clientAuthorizations = clientAuthorizationsService.findClientAuthorizations(user.getAttribute("inum"), client.getClientId());
                            if (clientAuthorizations != null && clientAuthorizations.getScopes() != null && Arrays.asList(clientAuthorizations.getScopes()).containsAll(scopes)) {
                                sessionUser.addPermission(clientId, true);
                            }
                            if (prompts.contains(Prompt.NONE) && client.getTrustedClient()) {
                                sessionUser.addPermission(clientId, true);
                            }
                            if (prompts.contains(Prompt.LOGIN)) {
                                endSession(sessionState, httpRequest, httpResponse);
                                sessionState = null;
                                prompts.remove(Prompt.LOGIN);
                                redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionState);
                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                return builder.build();
                            }
                            if (prompts.contains(Prompt.CONSENT) || !sessionUser.isPermissionGrantedForClient(clientId)) {
                                prompts.remove(Prompt.CONSENT);
                                redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionState);
                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                return builder.build();
                            }
                            // OXAUTH-37 : Validate authentication max age
                            boolean validAuthenticationMaxAge = true;
                            Integer authenticationMaxAge = null;
                            if (maxAge != null) {
                                authenticationMaxAge = maxAge;
                            } else if (!invalidOpenidRequestObject && jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null) {
                                authenticationMaxAge = jwtAuthorizationRequest.getIdTokenMember().getMaxAge();
                            }
                            GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
                            GregorianCalendar userAuthenticationTime = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
                            userAuthenticationTime.setTime(sessionUser.getAuthenticationTime());
                            if (authenticationMaxAge != null) {
                                userAuthenticationTime.add(Calendar.SECOND, authenticationMaxAge);
                                validAuthenticationMaxAge = userAuthenticationTime.after(now);
                            } else if (client.getDefaultMaxAge() != null) {
                                userAuthenticationTime.add(Calendar.SECOND, client.getDefaultMaxAge());
                                validAuthenticationMaxAge = userAuthenticationTime.after(now);
                            }
                            if (!validAuthenticationMaxAge) {
                                endSession(sessionState, httpRequest, httpResponse);
                                sessionState = null;
                                redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionState);
                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                                applicationAuditLogger.sendMessage(oAuth2AuditLog);
                                return builder.build();
                            }
                            AuthorizationCode authorizationCode = null;
                            if (responseTypes.contains(ResponseType.CODE)) {
                                authorizationGrant = authorizationGrantList.createAuthorizationCodeGrant(user, client, sessionUser.getAuthenticationTime());
                                authorizationGrant.setNonce(nonce);
                                authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest);
                                authorizationGrant.setScopes(scopes);
                                authorizationGrant.setCodeChallenge(codeChallenge);
                                authorizationGrant.setCodeChallengeMethod(codeChallengeMethod);
                                // Store acr_values
                                authorizationGrant.setAcrValues(acrValuesStr);
                                authorizationGrant.setSessionDn(sessionUser.getDn());
                                // call save after object modification!!!
                                authorizationGrant.save();
                                authorizationCode = authorizationGrant.getAuthorizationCode();
                                redirectUriResponse.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(jwtAuthorizationRequest);
                                    authorizationGrant.setScopes(scopes);
                                    // Store acr_values
                                    authorizationGrant.setAcrValues(acrValuesStr);
                                    authorizationGrant.setSessionDn(sessionUser.getDn());
                                    // call save after object modification!!!
                                    authorizationGrant.save();
                                }
                                newAccessToken = authorizationGrant.createAccessToken();
                                redirectUriResponse.addResponseParameter(AuthorizeResponseParam.ACCESS_TOKEN, newAccessToken.getCode());
                                redirectUriResponse.addResponseParameter(AuthorizeResponseParam.TOKEN_TYPE, newAccessToken.getTokenType().toString());
                                redirectUriResponse.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.createAuthorizationGrant(user, client, sessionUser.getAuthenticationTime());
                                    authorizationGrant.setNonce(nonce);
                                    authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest);
                                    authorizationGrant.setScopes(scopes);
                                    // Store authentication acr values
                                    authorizationGrant.setAcrValues(acrValuesStr);
                                    authorizationGrant.setSessionDn(sessionUser.getDn());
                                    // call save after object modification, call is asynchronous!!!
                                    authorizationGrant.save();
                                }
                                IdToken idToken = authorizationGrant.createIdToken(nonce, authorizationCode, newAccessToken, authorizationGrant, includeIdTokenClaims);
                                redirectUriResponse.addResponseParameter(AuthorizeResponseParam.ID_TOKEN, idToken.getCode());
                            }
                            if (authorizationGrant != null && StringHelper.isNotEmpty(acrValuesStr)) {
                                redirectUriResponse.addResponseParameter(AuthorizeResponseParam.ACR_VALUES, acrValuesStr);
                            }
                            //if (Boolean.valueOf(requestSessionState) && StringUtils.isBlank(sessionState) &&
                            if (sessionUser.getId() == null) {
                                final SessionState newSessionUser = sessionStateService.generateAuthenticatedSessionState(sessionUser.getUserDn(), prompt);
                                String newSessionState = newSessionUser.getId();
                                sessionUser.setId(newSessionState);
                                log.trace("newSessionState = {}", newSessionState);
                            }
                            redirectUriResponse.addResponseParameter(AuthorizeResponseParam.SESSION_STATE, sessionUser.getId());
                            redirectUriResponse.addResponseParameter(AuthorizeResponseParam.STATE, state);
                            if (scope != null && !scope.isEmpty()) {
                                scope = authorizationGrant.checkScopesPolicy(scope);
                                redirectUriResponse.addResponseParameter(AuthorizeResponseParam.SCOPE, scope);
                            }
                            clientService.updatAccessTime(client, false);
                            oAuth2AuditLog.setSuccess(true);
                            builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                            if (appConfiguration.getCustomHeadersWithAuthorizationResponse()) {
                                for (String key : customResponseHeaders.keySet()) {
                                    builder.header(key, customResponseHeaders.get(key));
                                }
                            }
                        }
                    } else {
                        // Invalid redirectUri
                        builder = error(Response.Status.BAD_REQUEST, AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, // 400
                        state);
                    }
                } else {
                    // Invalid responseTypes
                    // 400
                    builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                    builder.entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNSUPPORTED_RESPONSE_TYPE, state));
                }
            } else {
                builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state);
            }
        }
    //        } catch (AcrChangedException e) {
    //            builder = Response.status(Response.Status.UNAUTHORIZED).entity("Session already exist with ACR that is different " +
    //                    "than the one send with this authorization request. Please perform logout in order to login with another ACR. ACR: " + acrValuesStr);
    //            log.error(e.getMessage(), e);
    } catch (AcrChangedException e) {
        // Acr changed
        log.error("ACR is changed, please use prompt=login in order to alter existing session.");
        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 = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state);
        log.error(e.getMessage(), e);
    } catch (SignatureException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (StringEncrypter.EncryptionException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (InvalidJwtException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } 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 : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SessionState(org.xdi.oxauth.model.common.SessionState) User(org.xdi.oxauth.model.common.User) OAuth2AuditLog(org.xdi.oxauth.model.audit.OAuth2AuditLog) ArrayList(java.util.ArrayList) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) RedirectUri(org.xdi.oxauth.util.RedirectUri) URISyntaxException(java.net.URISyntaxException) SignatureException(java.security.SignatureException) URI(java.net.URI) AcrChangedException(org.xdi.oxauth.model.exception.AcrChangedException) AccessToken(org.xdi.oxauth.model.common.AccessToken) JwtAuthorizationRequest(org.xdi.oxauth.model.authorize.JwtAuthorizationRequest) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Client(org.xdi.oxauth.model.registration.Client) AuthorizationGrant(org.xdi.oxauth.model.common.AuthorizationGrant) ClientRequest(org.jboss.resteasy.client.ClientRequest) ConnectException(java.net.ConnectException) AuthorizationCode(org.xdi.oxauth.model.common.AuthorizationCode) IdToken(org.xdi.oxauth.model.common.IdToken) UnknownHostException(java.net.UnknownHostException) GregorianCalendar(java.util.GregorianCalendar) ClientAuthorizations(org.xdi.oxauth.model.ldap.ClientAuthorizations) StringEncrypter(org.xdi.util.security.StringEncrypter) AcrChangedException(org.xdi.oxauth.model.exception.AcrChangedException) URISyntaxException(java.net.URISyntaxException) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SignatureException(java.security.SignatureException) ConnectException(java.net.ConnectException) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) UnknownHostException(java.net.UnknownHostException) ResponseType(org.xdi.oxauth.model.common.ResponseType) AuthorizeErrorResponseType(org.xdi.oxauth.model.authorize.AuthorizeErrorResponseType) ResponseMode(org.xdi.oxauth.model.common.ResponseMode) Prompt(org.xdi.oxauth.model.common.Prompt) Claim(org.xdi.oxauth.model.authorize.Claim)

Example 5 with Prompt

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

the class AuthorizeAction method checkPermissionGranted.

public void checkPermissionGranted() {
    if ((clientId == null) || clientId.isEmpty()) {
        log.error("Permission denied. client_id should be not empty.");
        permissionDenied();
        return;
    }
    Client client = null;
    try {
        client = clientService.getClient(clientId);
    } catch (EntryPersistenceException ex) {
        log.error("Permission denied. Failed to find client by inum '{}' in LDAP.", clientId, ex);
        permissionDenied();
        return;
    }
    if (client == null) {
        log.error("Permission denied. Failed to find client_id '{}' in LDAP.", clientId);
        permissionDenied();
        return;
    }
    SessionState session = getSession();
    List<Prompt> prompts = Prompt.fromString(prompt, " ");
    try {
        session = sessionStateService.assertAuthenticatedSessionCorrespondsToNewRequest(session, acrValues);
    } catch (AcrChangedException e) {
        log.debug("There is already existing session which has another acr then {}, session: {}", acrValues, session.getId());
        if (prompts.contains(Prompt.LOGIN)) {
            session = handleAcrChange(session, prompts);
        } else {
            log.error("Please provide prompt=login to force login with new ACR or otherwise perform logout and re-authenticate.");
            permissionDenied();
            return;
        }
    }
    if (session == null || StringUtils.isBlank(session.getUserDn()) || SessionIdState.AUTHENTICATED != session.getState()) {
        Map<String, String> parameterMap = externalContext.getRequestParameterMap();
        Map<String, String> requestParameterMap = authenticationService.getAllowedParameters(parameterMap);
        String redirectTo = "/login.xhtml";
        boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
        if (useExternalAuthenticator) {
            List<String> acrValuesList = acrValuesList();
            if (acrValuesList.isEmpty()) {
                if (StringHelper.isNotEmpty(defaultAuthenticationMode.getName())) {
                    acrValuesList = Arrays.asList(defaultAuthenticationMode.getName());
                } else {
                    CustomScriptConfiguration defaultExternalAuthenticator = externalAuthenticationService.getDefaultExternalAuthenticator(AuthenticationScriptUsageType.INTERACTIVE);
                    if (defaultExternalAuthenticator != null) {
                        acrValuesList = Arrays.asList(defaultExternalAuthenticator.getName());
                    }
                }
            }
            CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, acrValuesList);
            if (customScriptConfiguration == null) {
                log.error("Failed to get CustomScriptConfiguration. auth_step: {}, acr_values: {}", 1, this.acrValues);
                permissionDenied();
                return;
            }
            String acr = customScriptConfiguration.getName();
            requestParameterMap.put(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, acr);
            requestParameterMap.put("auth_step", Integer.toString(1));
            String tmpRedirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, 1);
            if (StringHelper.isNotEmpty(tmpRedirectTo)) {
                log.trace("Redirect to person authentication login page: {}", tmpRedirectTo);
                redirectTo = tmpRedirectTo;
            }
        }
        // Store Remote IP
        String remoteIp = networkService.getRemoteIp();
        requestParameterMap.put(Constants.REMOTE_IP, remoteIp);
        // Create unauthenticated session
        SessionState unauthenticatedSession = sessionStateService.generateUnauthenticatedSessionState(null, new Date(), SessionIdState.UNAUTHENTICATED, requestParameterMap, false);
        unauthenticatedSession.setSessionAttributes(requestParameterMap);
        unauthenticatedSession.addPermission(clientId, false);
        // always persist is prompt is not none
        boolean persisted = sessionStateService.persistSessionState(unauthenticatedSession, !prompts.contains(Prompt.NONE));
        if (persisted && log.isTraceEnabled()) {
            log.trace("Session '{}' persisted to LDAP", unauthenticatedSession.getId());
        }
        this.sessionState = unauthenticatedSession.getId();
        sessionStateService.createSessionStateCookie(this.sessionState);
        Map<String, Object> loginParameters = new HashMap<String, Object>();
        if (requestParameterMap.containsKey(AuthorizeRequestParam.LOGIN_HINT)) {
            loginParameters.put(AuthorizeRequestParam.LOGIN_HINT, requestParameterMap.get(AuthorizeRequestParam.LOGIN_HINT));
        }
        facesService.redirect(redirectTo, loginParameters);
        return;
    }
    if (StringUtils.isBlank(redirectionUriService.validateRedirectionUri(clientId, redirectUri))) {
        permissionDenied();
    }
    final User user = userService.getUserByDn(session.getUserDn());
    log.trace("checkPermissionGranted, user = " + user);
    if (AuthorizeParamsValidator.noNonePrompt(prompts)) {
        if (appConfiguration.getTrustedClientEnabled()) {
            // if trusted client = true, then skip authorization page and grant access directly
            if (client.getTrustedClient() && !prompts.contains(Prompt.CONSENT)) {
                permissionGranted(session);
                return;
            }
        }
        if (client.getPersistClientAuthorizations()) {
            ClientAuthorizations clientAuthorizations = clientAuthorizationsService.findClientAuthorizations(user.getAttribute("inum"), client.getClientId());
            if (clientAuthorizations != null && clientAuthorizations.getScopes() != null && Arrays.asList(clientAuthorizations.getScopes()).containsAll(org.xdi.oxauth.model.util.StringUtils.spaceSeparatedToList(scope))) {
                permissionGranted(session);
                return;
            }
        }
    } else {
        invalidRequest();
    }
    return;
}
Also used : SessionState(org.xdi.oxauth.model.common.SessionState) User(org.xdi.oxauth.model.common.User) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) ClientAuthorizations(org.xdi.oxauth.model.ldap.ClientAuthorizations) AcrChangedException(org.xdi.oxauth.model.exception.AcrChangedException) Prompt(org.xdi.oxauth.model.common.Prompt) Client(org.xdi.oxauth.model.registration.Client) CustomScriptConfiguration(org.xdi.model.custom.script.conf.CustomScriptConfiguration)

Aggregations

Prompt (org.xdi.oxauth.model.common.Prompt)5 ResponseType (org.xdi.oxauth.model.common.ResponseType)3 User (org.xdi.oxauth.model.common.User)3 Client (org.xdi.oxauth.model.registration.Client)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 JSONArray (org.codehaus.jettison.json.JSONArray)2 JSONObject (org.codehaus.jettison.json.JSONObject)2 EntryPersistenceException (org.gluu.site.ldap.persistence.exception.EntryPersistenceException)2 SessionState (org.xdi.oxauth.model.common.SessionState)2 AcrChangedException (org.xdi.oxauth.model.exception.AcrChangedException)2 ClientAuthorizations (org.xdi.oxauth.model.ldap.ClientAuthorizations)2 ConnectException (java.net.ConnectException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 UnknownHostException (java.net.UnknownHostException)1 SignatureException (java.security.SignatureException)1 ArrayList (java.util.ArrayList)1 GregorianCalendar (java.util.GregorianCalendar)1 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)1 ClientRequest (org.jboss.resteasy.client.ClientRequest)1