Search in sources :

Example 1 with IdToken

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

the class TokenRestWebServiceImpl method requestAccessToken.

@Override
public Response requestAccessToken(String grantType, String code, String redirectUri, String username, String password, String scope, String assertion, String refreshToken, String oxAuthExchangeToken, String clientId, String clientSecret, String codeVerifier, HttpServletRequest request, SecurityContext sec) {
    log.debug("Attempting to request access token: grantType = {}, code = {}, redirectUri = {}, username = {}, refreshToken = {}, " + "clientId = {}, ExtraParams = {}, isSecure = {}, codeVerifier = {}", grantType, code, redirectUri, username, refreshToken, clientId, request.getParameterMap(), sec.isSecure(), codeVerifier);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REQUEST);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setUsername(username);
    oAuth2AuditLog.setScope(scope);
    // it may be encoded in uma case
    scope = ServerUtil.urlDecode(scope);
    ResponseBuilder builder = Response.ok();
    try {
        log.debug("Starting to validate request parameters");
        if (!TokenParamsValidator.validateParams(grantType, code, redirectUri, username, password, scope, assertion, refreshToken, oxAuthExchangeToken)) {
            log.trace("Failed to validate request parameters");
            builder = error(400, TokenErrorResponseType.INVALID_REQUEST);
        } else {
            log.trace("Request parameters are right");
            GrantType gt = GrantType.fromString(grantType);
            log.debug("Grant type: '{}'", gt);
            SessionClient sessionClient = identity.getSetSessionClient();
            Client client = null;
            if (sessionClient != null) {
                client = sessionClient.getClient();
                log.debug("Get sessionClient: '{}'", sessionClient);
            }
            if (client != null) {
                log.debug("Get client from session: '{}'", client.getClientId());
            }
            if (gt == GrantType.AUTHORIZATION_CODE) {
                if (client == null) {
                    return response(error(400, TokenErrorResponseType.INVALID_GRANT));
                }
                log.debug("Attempting to find authorizationCodeGrant by clinetId: '{}', code: '{}'", client.getClientId(), code);
                AuthorizationCodeGrant authorizationCodeGrant = authorizationGrantList.getAuthorizationCodeGrant(client.getClientId(), code);
                log.trace("AuthorizationCodeGrant : '{}'", authorizationCodeGrant);
                if (authorizationCodeGrant != null) {
                    validatePKCE(authorizationCodeGrant, codeVerifier);
                    authorizationCodeGrant.setIsCachedWithNoPersistence(false);
                    authorizationCodeGrant.save();
                    AccessToken accToken = authorizationCodeGrant.createAccessToken();
                    log.debug("Issuing access token: {}", accToken.getCode());
                    RefreshToken reToken = authorizationCodeGrant.createRefreshToken();
                    if (scope != null && !scope.isEmpty()) {
                        scope = authorizationCodeGrant.checkScopesPolicy(scope);
                    }
                    IdToken idToken = null;
                    if (authorizationCodeGrant.getScopes().contains("openid")) {
                        String nonce = authorizationCodeGrant.getNonce();
                        boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                        idToken = authorizationCodeGrant.createIdToken(nonce, null, accToken, authorizationCodeGrant, includeIdTokenClaims);
                    }
                    builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, idToken));
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationCodeGrant, true);
                    grantService.removeByCode(authorizationCodeGrant.getAuthorizationCode().getCode(), authorizationCodeGrant.getClientId());
                } else {
                    log.debug("AuthorizationCodeGrant is empty by clinetId: '{}', code: '{}'", client.getClientId(), code);
                    // if authorization code is not found then code was already used = remove all grants with this auth code
                    grantService.removeAllByAuthorizationCode(code);
                    builder = error(400, TokenErrorResponseType.INVALID_GRANT);
                }
            } else if (gt == GrantType.REFRESH_TOKEN) {
                if (client == null) {
                    return response(error(401, TokenErrorResponseType.INVALID_GRANT));
                }
                AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), refreshToken);
                if (authorizationGrant != null) {
                    AccessToken accToken = authorizationGrant.createAccessToken();
                    /*
                        The authorization server MAY issue a new refresh token, in which case
                        the client MUST discard the old refresh token and replace it with the
                        new refresh token.
                        */
                    RefreshToken reToken = authorizationGrant.createRefreshToken();
                    grantService.removeByCode(refreshToken, client.getClientId());
                    if (scope != null && !scope.isEmpty()) {
                        scope = authorizationGrant.checkScopesPolicy(scope);
                    }
                    builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, null));
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                } else {
                    builder = error(401, TokenErrorResponseType.INVALID_GRANT);
                }
            } else if (gt == GrantType.CLIENT_CREDENTIALS) {
                if (client == null) {
                    return response(error(401, TokenErrorResponseType.INVALID_GRANT));
                }
                // TODO: fix the user arg
                ClientCredentialsGrant clientCredentialsGrant = authorizationGrantList.createClientCredentialsGrant(new User(), client);
                AccessToken accessToken = clientCredentialsGrant.createAccessToken();
                if (scope != null && !scope.isEmpty()) {
                    scope = clientCredentialsGrant.checkScopesPolicy(scope);
                }
                IdToken idToken = null;
                if (clientCredentialsGrant.getScopes().contains("openid")) {
                    boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                    idToken = clientCredentialsGrant.createIdToken(null, null, null, clientCredentialsGrant, includeIdTokenClaims);
                }
                oAuth2AuditLog.updateOAuth2AuditLog(clientCredentialsGrant, true);
                builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, scope, idToken));
            } else if (gt == GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS) {
                if (client == null) {
                    log.error("Invalid client", new RuntimeException("Client is empty"));
                    return response(error(401, TokenErrorResponseType.INVALID_CLIENT));
                }
                User user = null;
                if (authenticationFilterService.isEnabled()) {
                    String userDn = authenticationFilterService.processAuthenticationFilters(request.getParameterMap());
                    if (StringHelper.isNotEmpty(userDn)) {
                        user = userService.getUserByDn(userDn);
                    }
                }
                if (user == null) {
                    boolean authenticated = authenticationService.authenticate(username, password);
                    if (authenticated) {
                        user = authenticationService.getAuthenticatedUser();
                    }
                }
                if (user != null) {
                    ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = authorizationGrantList.createResourceOwnerPasswordCredentialsGrant(user, client);
                    AccessToken accessToken = resourceOwnerPasswordCredentialsGrant.createAccessToken();
                    RefreshToken reToken = resourceOwnerPasswordCredentialsGrant.createRefreshToken();
                    if (scope != null && !scope.isEmpty()) {
                        scope = resourceOwnerPasswordCredentialsGrant.checkScopesPolicy(scope);
                    }
                    IdToken idToken = null;
                    if (resourceOwnerPasswordCredentialsGrant.getScopes().contains("openid")) {
                        boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                        idToken = resourceOwnerPasswordCredentialsGrant.createIdToken(null, null, null, resourceOwnerPasswordCredentialsGrant, includeIdTokenClaims);
                    }
                    oAuth2AuditLog.updateOAuth2AuditLog(resourceOwnerPasswordCredentialsGrant, true);
                    builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), reToken, scope, idToken));
                } else {
                    log.error("Invalid user", new RuntimeException("User is empty"));
                    builder = error(401, TokenErrorResponseType.INVALID_CLIENT);
                }
            } else if (gt == GrantType.EXTENSION) {
                builder = error(501, TokenErrorResponseType.INVALID_GRANT);
            } else if (gt == GrantType.OXAUTH_EXCHANGE_TOKEN) {
                AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(oxAuthExchangeToken);
                if (authorizationGrant != null) {
                    final AccessToken accessToken = authorizationGrant.createLongLivedAccessToken();
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                    builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, null, null));
                } else {
                    builder = error(401, TokenErrorResponseType.INVALID_GRANT);
                }
            }
        }
    } catch (WebApplicationException e) {
        throw e;
    } catch (SignatureException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (StringEncrypter.EncryptionException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (InvalidJwtException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (InvalidJweException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return response(builder);
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) IdToken(org.xdi.oxauth.model.common.IdToken) User(org.xdi.oxauth.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(org.xdi.oxauth.model.session.SessionClient) OAuth2AuditLog(org.xdi.oxauth.model.audit.OAuth2AuditLog) ResourceOwnerPasswordCredentialsGrant(org.xdi.oxauth.model.common.ResourceOwnerPasswordCredentialsGrant) GrantType(org.xdi.oxauth.model.common.GrantType) SignatureException(java.security.SignatureException) StringEncrypter(org.xdi.util.security.StringEncrypter) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SignatureException(java.security.SignatureException) JSONException(org.codehaus.jettison.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) RefreshToken(org.xdi.oxauth.model.common.RefreshToken) AuthorizationCodeGrant(org.xdi.oxauth.model.common.AuthorizationCodeGrant) AccessToken(org.xdi.oxauth.model.common.AccessToken) ClientCredentialsGrant(org.xdi.oxauth.model.common.ClientCredentialsGrant) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Client(org.xdi.oxauth.model.registration.Client) SessionClient(org.xdi.oxauth.model.session.SessionClient) AuthorizationGrant(org.xdi.oxauth.model.common.AuthorizationGrant) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException)

Example 2 with IdToken

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

the class PersistentJwt method load.

private boolean load(String jwt) throws JSONException {
    boolean result = false;
    JSONObject jsonObject = new JSONObject(jwt);
    if (jsonObject.has("user_id")) {
        userId = jsonObject.getString("user_id");
    }
    if (jsonObject.has("client_id")) {
        clientId = jsonObject.getString("client_id");
    }
    if (jsonObject.has("authorization_grant_type")) {
        authorizationGrantType = AuthorizationGrantType.fromString(jsonObject.getString("authorization_grant_type"));
    }
    if (jsonObject.has("authentication_time")) {
        authenticationTime = new Date(jsonObject.getLong("authentication_time"));
    }
    if (jsonObject.has("scopes")) {
        JSONArray jsonArray = jsonObject.getJSONArray("scopes");
        scopes = Util.asList(jsonArray);
    }
    if (jsonObject.has("access_tokens")) {
        JSONArray accessTokensJsonArray = jsonObject.getJSONArray("access_tokens");
        accessTokens = new ArrayList<AccessToken>();
        for (int i = 0; i < accessTokensJsonArray.length(); i++) {
            JSONObject accessTokenJsonObject = accessTokensJsonArray.getJSONObject(i);
            if (accessTokenJsonObject.has("code") && accessTokenJsonObject.has("creation_date") && accessTokenJsonObject.has("expiration_date")) {
                String tokenCode = accessTokenJsonObject.getString("code");
                Date creationDate = new Date(accessTokenJsonObject.getLong("creation_date"));
                Date expirationDate = new Date(accessTokenJsonObject.getLong("expiration_date"));
                AccessToken accessToken = new AccessToken(tokenCode, creationDate, expirationDate);
                accessTokens.add(accessToken);
            }
        }
    }
    if (jsonObject.has("refresh_tokens")) {
        JSONArray refreshTokensJsonArray = jsonObject.getJSONArray("refresh_tokens");
        refreshTokens = new ArrayList<RefreshToken>();
        for (int i = 0; i < refreshTokensJsonArray.length(); i++) {
            JSONObject refreshTokenJsonObject = refreshTokensJsonArray.getJSONObject(i);
            if (refreshTokenJsonObject.has("code") && refreshTokenJsonObject.has("creation_date") && refreshTokenJsonObject.has("expiration_date")) {
                String tokenCode = refreshTokenJsonObject.getString("code");
                Date creationDate = new Date(refreshTokenJsonObject.getLong("creation_date"));
                Date expirationDate = new Date(refreshTokenJsonObject.getLong("expiration_date"));
                RefreshToken refreshToken = new RefreshToken(tokenCode, creationDate, expirationDate);
                refreshTokens.add(refreshToken);
            }
        }
    }
    if (jsonObject.has("long_lived_access_token")) {
        JSONObject longLivedAccessTokenJsonObject = jsonObject.getJSONObject("long_lived_access_token");
        if (longLivedAccessTokenJsonObject.has("code") && longLivedAccessTokenJsonObject.has("creation_date") && longLivedAccessTokenJsonObject.has("expiration_date")) {
            String tokenCode = longLivedAccessTokenJsonObject.getString("code");
            Date creationDate = new Date(longLivedAccessTokenJsonObject.getLong("creation_date"));
            Date expirationDate = new Date(longLivedAccessTokenJsonObject.getLong("expiration_date"));
            longLivedAccessToken = new AccessToken(tokenCode, creationDate, expirationDate);
        }
    }
    if (jsonObject.has("id_token")) {
        JSONObject idTokenJsonObject = jsonObject.getJSONObject("id_token");
        if (idTokenJsonObject.has("code") && idTokenJsonObject.has("creation_date") && idTokenJsonObject.has("expiration_date")) {
            String tokenCode = idTokenJsonObject.getString("code");
            Date creationDate = new Date(idTokenJsonObject.getLong("creation_date"));
            Date expirationDate = new Date(idTokenJsonObject.getLong("expiration_date"));
            idToken = new IdToken(tokenCode, creationDate, expirationDate);
        }
    }
    return result;
}
Also used : IdToken(org.xdi.oxauth.model.common.IdToken) RefreshToken(org.xdi.oxauth.model.common.RefreshToken) JSONObject(org.codehaus.jettison.json.JSONObject) AccessToken(org.xdi.oxauth.model.common.AccessToken) JSONArray(org.codehaus.jettison.json.JSONArray) Date(java.util.Date)

Example 3 with IdToken

use of org.xdi.oxauth.model.common.IdToken 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)

Aggregations

AccessToken (org.xdi.oxauth.model.common.AccessToken)3 IdToken (org.xdi.oxauth.model.common.IdToken)3 SignatureException (java.security.SignatureException)2 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)2 OAuth2AuditLog (org.xdi.oxauth.model.audit.OAuth2AuditLog)2 AuthorizationGrant (org.xdi.oxauth.model.common.AuthorizationGrant)2 RefreshToken (org.xdi.oxauth.model.common.RefreshToken)2 User (org.xdi.oxauth.model.common.User)2 InvalidJwtException (org.xdi.oxauth.model.exception.InvalidJwtException)2 Client (org.xdi.oxauth.model.registration.Client)2 StringEncrypter (org.xdi.util.security.StringEncrypter)2 ConnectException (java.net.ConnectException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 UnknownHostException (java.net.UnknownHostException)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 GregorianCalendar (java.util.GregorianCalendar)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 JSONArray (org.codehaus.jettison.json.JSONArray)1