Search in sources :

Example 1 with AccessToken

use of io.jans.as.server.model.common.AccessToken in project jans by JanssenProject.

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(io.jans.as.server.model.common.IdToken) RefreshToken(io.jans.as.server.model.common.RefreshToken) JSONObject(org.json.JSONObject) AccessToken(io.jans.as.server.model.common.AccessToken) JSONArray(org.json.JSONArray) Date(java.util.Date)

Example 2 with AccessToken

use of io.jans.as.server.model.common.AccessToken in project jans by JanssenProject.

the class PersistentJwt method toString.

@Override
public String toString() {
    JSONObject jsonObject = new JSONObject();
    try {
        if (StringUtils.isNotBlank(userId)) {
            jsonObject.put("user_id", userId);
        }
        if (StringUtils.isNotBlank(clientId)) {
            jsonObject.put("client_id", clientId);
        }
        if (authorizationGrantType != null) {
            jsonObject.put("authorization_grant_type", authorizationGrantType);
        }
        if (authenticationTime != null) {
            jsonObject.put("authentication_time", authenticationTime.getTime());
        }
        if (scopes != null) {
            JSONArray scopesJsonArray = new JSONArray();
            for (String scope : scopes) {
                scopesJsonArray.put(scope);
            }
            jsonObject.put("scopes", scopesJsonArray);
        }
        if (accessTokens != null) {
            JSONArray accessTokensJsonArray = new JSONArray();
            for (AccessToken accessToken : accessTokens) {
                JSONObject accessTokenJsonObject = new JSONObject();
                if (accessToken.getCode() != null && !accessToken.getCode().isEmpty()) {
                    accessTokenJsonObject.put("code", accessToken.getCode());
                }
                if (accessToken.getCreationDate() != null) {
                    accessTokenJsonObject.put("creation_date", accessToken.getCreationDate().getTime());
                }
                if (accessToken.getExpirationDate() != null) {
                    accessTokenJsonObject.put("expiration_date", accessToken.getExpirationDate().getTime());
                }
                accessTokensJsonArray.put(accessTokenJsonObject);
            }
            jsonObject.put("access_tokens", accessTokensJsonArray);
        }
        if (refreshTokens != null) {
            JSONArray refreshTokensJsonArray = new JSONArray();
            for (RefreshToken refreshToken : refreshTokens) {
                JSONObject refreshTokenJsonObject = new JSONObject();
                if (refreshToken.getCode() != null && !refreshToken.getCode().isEmpty()) {
                    refreshTokenJsonObject.put("code", refreshToken.getCode());
                }
                if (refreshToken.getCreationDate() != null) {
                    refreshTokenJsonObject.put("creation_date", refreshToken.getCreationDate().getTime());
                }
                if (refreshToken.getExpirationDate() != null) {
                    refreshTokenJsonObject.put("expiration_date", refreshToken.getExpirationDate().getTime());
                }
            }
            jsonObject.put("refresh_tokens", refreshTokensJsonArray);
        }
        if (longLivedAccessToken != null) {
            JSONObject longLivedAccessTokenJsonObject = new JSONObject();
            if (longLivedAccessToken.getCode() != null && !longLivedAccessToken.getCode().isEmpty()) {
                longLivedAccessTokenJsonObject.put("code", longLivedAccessToken.getCode());
            }
            if (longLivedAccessToken.getCreationDate() != null) {
                longLivedAccessTokenJsonObject.put("creation_date", longLivedAccessToken.getCreationDate().getTime());
            }
            if (longLivedAccessToken.getExpirationDate() != null) {
                longLivedAccessTokenJsonObject.put("expiration_date", longLivedAccessToken.getExpirationDate().getTime());
            }
            jsonObject.put("long_lived_access_token", longLivedAccessTokenJsonObject);
        }
        if (idToken != null) {
            JSONObject idTokenJsonObject = new JSONObject();
            if (idToken.getCode() != null && !idToken.getCode().isEmpty()) {
                idTokenJsonObject.put("code", idToken.getCode());
            }
            if (idToken.getCreationDate() != null) {
                idTokenJsonObject.put("creation_date", idToken.getCreationDate().getTime());
            }
            if (idToken.getExpirationDate() != null) {
                idTokenJsonObject.put("expiration_date", idToken.getExpirationDate().getTime());
            }
            jsonObject.put("id_token", idTokenJsonObject);
        }
    } catch (JSONException e) {
        log.error(e.getMessage(), e);
    }
    return jsonObject.toString();
}
Also used : RefreshToken(io.jans.as.server.model.common.RefreshToken) JSONObject(org.json.JSONObject) AccessToken(io.jans.as.server.model.common.AccessToken) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Example 3 with AccessToken

use of io.jans.as.server.model.common.AccessToken in project jans by JanssenProject.

the class IntrospectionWebService method fillResponse.

@Nullable
private AbstractToken fillResponse(String token, IntrospectionResponse response, AuthorizationGrant grantOfIntrospectionToken) {
    AbstractToken tokenToIntrospect = null;
    if (grantOfIntrospectionToken != null) {
        tokenToIntrospect = grantOfIntrospectionToken.getAccessToken(token);
        response.setActive(tokenToIntrospect.isValid());
        response.setExpiresAt(ServerUtil.dateToSeconds(tokenToIntrospect.getExpirationDate()));
        response.setIssuedAt(ServerUtil.dateToSeconds(tokenToIntrospect.getCreationDate()));
        response.setAcrValues(grantOfIntrospectionToken.getAcrValues());
        // #433
        response.setScope(grantOfIntrospectionToken.getScopes() != null ? grantOfIntrospectionToken.getScopes() : Lists.newArrayList());
        response.setClientId(grantOfIntrospectionToken.getClientId());
        response.setSub(grantOfIntrospectionToken.getSub());
        response.setUsername(grantOfIntrospectionToken.getUserId());
        response.setIssuer(appConfiguration.getIssuer());
        response.setAudience(grantOfIntrospectionToken.getClientId());
        if (tokenToIntrospect instanceof AccessToken) {
            AccessToken accessToken = (AccessToken) tokenToIntrospect;
            response.setTokenType(accessToken.getTokenType() != null ? accessToken.getTokenType().getName() : io.jans.as.model.common.TokenType.BEARER.getName());
            // DPoP
            if (StringUtils.isNotBlank(accessToken.getDpop())) {
                response.setNotBefore(accessToken.getCreationDate().getTime());
                HashMap<String, String> cnf = new HashMap<>();
                cnf.put("jkt", accessToken.getDpop());
                response.setCnf(cnf);
            }
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Failed to find grant for access_token: {}. Return 200 with active=false.", escapeLog(token));
    }
    return tokenToIntrospect;
}
Also used : AbstractToken(io.jans.as.server.model.common.AbstractToken) HashMap(java.util.HashMap) AccessToken(io.jans.as.server.model.common.AccessToken) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with AccessToken

use of io.jans.as.server.model.common.AccessToken in project jans by JanssenProject.

the class TokenRestWebServiceImpl method processDeviceCodeGrantType.

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

Example 5 with AccessToken

use of io.jans.as.server.model.common.AccessToken in project jans by JanssenProject.

the class TokenRestWebServiceImpl method requestAccessToken.

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

Aggregations

AccessToken (io.jans.as.server.model.common.AccessToken)6 ExecutionContext (io.jans.as.server.model.common.ExecutionContext)3 RefreshToken (io.jans.as.server.model.common.RefreshToken)3 User (io.jans.as.common.model.common.User)2 Client (io.jans.as.common.model.registration.Client)2 ClientCredentialsGrant (io.jans.as.server.model.common.ClientCredentialsGrant)2 DeviceAuthorizationCacheControl (io.jans.as.server.model.common.DeviceAuthorizationCacheControl)2 DeviceCodeGrant (io.jans.as.server.model.common.DeviceCodeGrant)2 IdToken (io.jans.as.server.model.common.IdToken)2 Date (java.util.Date)2 JSONArray (org.json.JSONArray)2 JSONObject (org.json.JSONObject)2 Strings (com.google.common.base.Strings)1 JWKException (com.nimbusds.jose.jwk.JWKException)1 AttributeService (io.jans.as.common.service.AttributeService)1 CodeVerifier (io.jans.as.model.authorize.CodeVerifier)1 BackchannelTokenDeliveryMode (io.jans.as.model.common.BackchannelTokenDeliveryMode)1 ComponentType (io.jans.as.model.common.ComponentType)1 GrantType (io.jans.as.model.common.GrantType)1 ScopeConstants (io.jans.as.model.common.ScopeConstants)1