Search in sources :

Example 6 with AbstractToken

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

the class AuthenticationFilter method processAuthByAccessToken.

private void processAuthByAccessToken(String accessToken, HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain) {
    try {
        log.trace("Authenticating client by access token {} ...", accessToken);
        if (StringUtils.isBlank(accessToken)) {
            sendError(httpResponse);
            return;
        }
        AuthorizationGrant grant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
        if (grant == null) {
            sendError(httpResponse);
            return;
        }
        final AbstractToken accessTokenObj = grant.getAccessToken(accessToken);
        if (accessTokenObj == null || !accessTokenObj.isValid()) {
            sendError(httpResponse);
            return;
        }
        Client client = grant.getClient();
        authenticator.configureSessionClient(client);
        filterChain.doFilter(httpRequest, httpResponse);
        return;
    } catch (Exception ex) {
        log.error("Failed to authenticate client by access_token", ex);
    }
    sendError(httpResponse);
}
Also used : AbstractToken(io.jans.as.server.model.common.AbstractToken) Client(io.jans.as.common.model.registration.Client) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) ServletException(javax.servlet.ServletException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException)

Example 7 with AbstractToken

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

the class UserInfoRestWebServiceImpl method requestUserInfo.

private Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
    if (tokenService.isBearerAuthToken(authorization)) {
        accessToken = tokenService.getBearerToken(authorization);
    }
    log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
    errorResponseFactory.validateComponentEnabled(ComponentType.USERINFO);
    Response.ResponseBuilder builder = Response.ok();
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
    try {
        if (!UserInfoParamsValidator.validateParams(accessToken)) {
            return response(400, UserInfoErrorResponseType.INVALID_REQUEST, "access token is not valid.");
        }
        AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
        if (authorizationGrant == null) {
            log.trace("Failed to find authorization grant by access_token: {}", accessToken);
            return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
        }
        oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
        final AbstractToken accessTokenObject = authorizationGrant.getAccessToken(accessToken);
        if (accessTokenObject == null || !accessTokenObject.isValid()) {
            log.trace("Invalid access token object, access_token: {}, isNull: {}, isValid: {}", accessToken, accessTokenObject == null, false);
            return response(401, UserInfoErrorResponseType.INVALID_TOKEN);
        }
        if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Grant object has client_credentials grant_type which is not valid.");
        }
        if (appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Both openid and profile scopes are not present.");
        }
        if (!appConfiguration.getOpenidScopeBackwardCompatibility() && !authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString())) {
            return response(403, UserInfoErrorResponseType.INSUFFICIENT_SCOPE, "Missed openid scope.");
        }
        oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
        builder.cacheControl(ServerUtil.cacheControlWithNoStoreTransformAndPrivate());
        builder.header(Constants.PRAGMA, Constants.NO_CACHE);
        User currentUser = authorizationGrant.getUser();
        try {
            currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
        } catch (EntryPersistenceException ex) {
            log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
        }
        if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
            KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
            BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
            builder.type("application/jwt");
            builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
        } else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
            SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
            builder.type("application/jwt");
            builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
        } else {
            builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
            builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
        }
        return builder.build();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        // 500
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
    } finally {
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
    }
}
Also used : JsonWebResponse(io.jans.as.model.token.JsonWebResponse) Response(javax.ws.rs.core.Response) User(io.jans.as.common.model.common.User) AbstractToken(io.jans.as.server.model.common.AbstractToken) OAuth2AuditLog(io.jans.as.server.model.audit.OAuth2AuditLog) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) UnmodifiableAuthorizationGrant(io.jans.as.server.model.common.UnmodifiableAuthorizationGrant) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) InvalidClaimException(io.jans.as.model.exception.InvalidClaimException) ParseException(java.text.ParseException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) InvalidJweException(io.jans.as.model.exception.InvalidJweException) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)

Example 8 with AbstractToken

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

the class IntrospectionWebService method introspect.

private Response introspect(String authorization, String token, String tokenTypeHint, String responseAsJwt, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        if (log.isTraceEnabled()) {
            log.trace("Introspect token, authorization: {}, token to introspect: {}, tokenTypeHint: {}", escapeLog(authorization), escapeLog(token), escapeLog(tokenTypeHint));
        }
        AuthorizationGrant authorizationGrant = validateAuthorization(authorization, token);
        if (StringUtils.isBlank(token)) {
            log.trace("Bad request: Token is blank.");
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, "")).build();
        }
        final io.jans.as.model.common.IntrospectionResponse response = new io.jans.as.model.common.IntrospectionResponse(false);
        final AuthorizationGrant grantOfIntrospectionToken = authorizationGrantList.getAuthorizationGrantByAccessToken(token);
        AbstractToken tokenToIntrospect = fillResponse(token, response, grantOfIntrospectionToken);
        JSONObject responseAsJsonObject = createResponseAsJsonObject(response, tokenToIntrospect);
        ExternalIntrospectionContext context = new ExternalIntrospectionContext(authorizationGrant, httpRequest, httpResponse, appConfiguration, attributeService);
        context.setGrantOfIntrospectionToken(grantOfIntrospectionToken);
        if (externalIntrospectionService.executeExternalModifyResponse(responseAsJsonObject, context)) {
            log.trace("Successfully run external introspection scripts.");
        } else {
            responseAsJsonObject = createResponseAsJsonObject(response, tokenToIntrospect);
            log.trace("Canceled changes made by external introspection script since method returned `false`.");
        }
        // Make scopes conform as required by spec, see #1499
        if (response.getScope() != null && !appConfiguration.getIntrospectionResponseScopesBackwardCompatibility()) {
            String scopes = StringUtils.join(response.getScope().toArray(), " ");
            responseAsJsonObject.put("scope", scopes);
        }
        if (Boolean.TRUE.toString().equalsIgnoreCase(responseAsJwt)) {
            return Response.status(Response.Status.OK).entity(createResponseAsJwt(responseAsJsonObject, grantOfIntrospectionToken)).build();
        }
        return Response.status(Response.Status.OK).entity(responseAsJsonObject.toString()).type(MediaType.APPLICATION_JSON_TYPE).build();
    } catch (WebApplicationException e) {
        if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
        }
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON_TYPE).build();
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) IntrospectionResponse(io.jans.as.model.common.IntrospectionResponse) JSONException(org.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) AbstractToken(io.jans.as.server.model.common.AbstractToken) JSONObject(org.json.JSONObject) IntrospectionResponse(io.jans.as.model.common.IntrospectionResponse) ExternalIntrospectionContext(io.jans.as.server.service.external.context.ExternalIntrospectionContext) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant)

Example 9 with AbstractToken

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

the class IntrospectionWebService method getAuthorizationGrant.

/**
 * @return we return pair of authorization grant or otherwise true - if it's basic client authentication or false if it is not
 * @throws UnsupportedEncodingException when encoding is not supported
 */
private Pair<AuthorizationGrant, Boolean> getAuthorizationGrant(String authorization, String accessToken) throws UnsupportedEncodingException {
    AuthorizationGrant grant = tokenService.getBearerAuthorizationGrant(authorization);
    if (grant != null) {
        final String authorizationAccessToken = tokenService.getBearerToken(authorization);
        final AbstractToken accessTokenObject = grant.getAccessToken(authorizationAccessToken);
        if (accessTokenObject != null && accessTokenObject.isValid()) {
            return new Pair<>(grant, false);
        } else {
            log.error("Access token is not valid: {}", authorizationAccessToken);
            return EMPTY;
        }
    }
    grant = tokenService.getBasicAuthorizationGrant(authorization);
    if (grant != null) {
        return new Pair<>(grant, false);
    }
    if (tokenService.isBasicAuthToken(authorization)) {
        return isBasicTokenValid(authorization, accessToken);
    }
    return EMPTY;
}
Also used : AbstractToken(io.jans.as.server.model.common.AbstractToken) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) Pair(io.jans.util.Pair)

Example 10 with AbstractToken

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

the class IntrospectionWebService method validateAuthorization.

private AuthorizationGrant validateAuthorization(String authorization, String token) throws UnsupportedEncodingException {
    final boolean skipAuthorization = isTrue(appConfiguration.getIntrospectionSkipAuthorization());
    log.trace("skipAuthorization: {}", skipAuthorization);
    if (skipAuthorization) {
        return null;
    }
    if (StringUtils.isBlank(authorization)) {
        log.trace("Bad request: Authorization header or token is blank.");
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, "")).build());
    }
    final Pair<AuthorizationGrant, Boolean> pair = getAuthorizationGrant(authorization, token);
    final AuthorizationGrant authorizationGrant = pair.getFirst();
    if (authorizationGrant == null) {
        log.error("Authorization grant is null.");
        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.ACCESS_DENIED, "Authorization grant is null.")).build());
    }
    final AbstractToken authorizationAccessToken = authorizationGrant.getAccessToken(tokenService.getToken(authorization));
    if ((authorizationAccessToken == null || !authorizationAccessToken.isValid()) && BooleanUtils.isFalse(pair.getSecond())) {
        log.error("Access token is not valid. Valid: {}, basicClientAuthentication: {}", (authorizationAccessToken != null && authorizationAccessToken.isValid()), pair.getSecond());
        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.ACCESS_DENIED, "Access token is not valid")).build());
    }
    if (isTrue(appConfiguration.getIntrospectionAccessTokenMustHaveUmaProtectionScope()) && !authorizationGrant.getScopesAsString().contains(UmaScopeType.PROTECTION.getValue())) {
        // #562 - make uma_protection optional
        final String reason = "access_token used to access introspection endpoint does not have uma_protection scope, however in oxauth configuration `checkUmaProtectionScopePresenceDuringIntrospection` is true";
        log.trace(reason);
        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.ACCESS_DENIED, reason)).type(MediaType.APPLICATION_JSON_TYPE).build());
    }
    return authorizationGrant;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) AbstractToken(io.jans.as.server.model.common.AbstractToken) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant)

Aggregations

AbstractToken (io.jans.as.server.model.common.AbstractToken)10 AuthorizationGrant (io.jans.as.server.model.common.AuthorizationGrant)9 WebApplicationException (javax.ws.rs.WebApplicationException)5 IOException (java.io.IOException)2 Response (javax.ws.rs.core.Response)2 User (io.jans.as.common.model.common.User)1 Client (io.jans.as.common.model.registration.Client)1 IntrospectionResponse (io.jans.as.model.common.IntrospectionResponse)1 BlockEncryptionAlgorithm (io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)1 KeyEncryptionAlgorithm (io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm)1 SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)1 InvalidClaimException (io.jans.as.model.exception.InvalidClaimException)1 InvalidJweException (io.jans.as.model.exception.InvalidJweException)1 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)1 JsonWebResponse (io.jans.as.model.token.JsonWebResponse)1 OAuth2AuditLog (io.jans.as.server.model.audit.OAuth2AuditLog)1 AccessToken (io.jans.as.server.model.common.AccessToken)1 UnmodifiableAuthorizationGrant (io.jans.as.server.model.common.UnmodifiableAuthorizationGrant)1 ExternalIntrospectionContext (io.jans.as.server.service.external.context.ExternalIntrospectionContext)1 EntryPersistenceException (io.jans.orm.exception.EntryPersistenceException)1