Search in sources :

Example 71 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project keycloak by keycloak.

the class JaxrsBearerTokenFilterImpl method propagateSecurityContext.

protected void propagateSecurityContext(JaxrsHttpFacade facade, ContainerRequestContext request, KeycloakDeployment resolvedDeployment, BearerTokenRequestAuthenticator bearer) {
    RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(resolvedDeployment, null, bearer.getTokenString(), bearer.getToken(), null, null, null);
    // Not needed to do resteasy specifics as KeycloakSecurityContext can be always retrieved from SecurityContext by typecast SecurityContext.getUserPrincipal to KeycloakPrincipal
    // ResteasyProviderFactory.pushContext(KeycloakSecurityContext.class, skSession);
    facade.setSecurityContext(skSession);
    String principalName = AdapterUtils.getPrincipalName(resolvedDeployment, bearer.getToken());
    final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(principalName, skSession);
    SecurityContext anonymousSecurityContext = getRequestSecurityContext(request);
    final boolean isSecure = anonymousSecurityContext.isSecure();
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(skSession);
    SecurityContext ctx = new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return principal;
        }

        @Override
        public boolean isUserInRole(String role) {
            return roles.contains(role);
        }

        @Override
        public boolean isSecure() {
            return isSecure;
        }

        @Override
        public String getAuthenticationScheme() {
            return "OAUTH_BEARER";
        }
    };
    request.setSecurityContext(ctx);
}
Also used : RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext) SecurityContext(javax.ws.rs.core.SecurityContext) RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 72 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project openscoring by openscoring.

the class NetworkSecurityContextFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    SecurityContext securityContext = new NetworkSecurityContext(this.request) {

        private Set<String> trustedAddresses = NetworkSecurityContextFilter.this.trustedAddresses;

        @Override
        public boolean isTrusted(String address) {
            return (this.trustedAddresses).contains(address) || (this.trustedAddresses).contains("*");
        }
    };
    requestContext.setSecurityContext(securityContext);
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) SecurityContext(javax.ws.rs.core.SecurityContext)

Example 73 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project oxAuth by GluuFederation.

the class RevokeSessionRestWebService method requestRevokeSession.

@POST
@Path("/revoke_session")
@Produces({ MediaType.APPLICATION_JSON })
public Response requestRevokeSession(@FormParam("user_criterion_key") String userCriterionKey, @FormParam("user_criterion_value") String userCriterionValue, @Context HttpServletRequest request, @Context HttpServletResponse response, @Context SecurityContext sec) {
    try {
        log.debug("Attempting to revoke session: userCriterionKey = {}, userCriterionValue = {}, isSecure = {}", userCriterionKey, userCriterionValue, sec.isSecure());
        validateAccess();
        final User user = userService.getUserByAttribute(userCriterionKey, userCriterionValue);
        if (user == null) {
            log.trace("Unable to find user by {}={}", userCriterionKey, userCriterionValue);
            // no error because we don't want to disclose internal AS info about users
            return Response.ok().build();
        }
        List<SessionId> sessionIdList = sessionIdService.findByUser(user.getDn());
        if (sessionIdList == null || sessionIdList.isEmpty()) {
            log.trace("No sessions found for user uid: {}, dn: {}", user.getUserId(), user.getDn());
            return Response.ok().build();
        }
        final List<SessionId> authenticatedSessions = sessionIdList.stream().filter(sessionId -> sessionId.getState() == SessionIdState.AUTHENTICATED).collect(Collectors.toList());
        sessionIdService.remove(authenticatedSessions);
        log.debug("Revoked {} user's sessions (user: {})", authenticatedSessions.size(), user.getUserId());
        return Response.ok().build();
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.status(500).build();
    }
}
Also used : UserService(org.gluu.oxauth.service.UserService) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) Context(javax.ws.rs.core.Context) SessionClient(org.gluu.oxauth.model.session.SessionClient) Identity(org.gluu.oxauth.security.Identity) HttpServletResponse(javax.servlet.http.HttpServletResponse) SecurityContext(javax.ws.rs.core.SecurityContext) Collectors(java.util.stream.Collectors) ScopeService(org.gluu.oxauth.service.ScopeService) SessionId(org.gluu.oxauth.model.common.SessionId) SessionIdState(org.gluu.oxauth.model.common.SessionIdState) Constants(org.gluu.oxauth.model.config.Constants) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) List(java.util.List) SessionIdService(org.gluu.oxauth.service.SessionIdService) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) User(org.gluu.oxauth.model.common.User) ErrorResponseFactory(org.gluu.oxauth.model.error.ErrorResponseFactory) EndSessionErrorResponseType(org.gluu.oxauth.model.session.EndSessionErrorResponseType) ArrayUtils(org.apache.commons.lang.ArrayUtils) User(org.gluu.oxauth.model.common.User) SessionId(org.gluu.oxauth.model.common.SessionId)

Example 74 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project oxAuth by GluuFederation.

the class TokenRestWebServiceImpl method requestAccessToken.

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

Example 75 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project graylog2-server by Graylog2.

the class SearchUserFactory method provide.

@Override
public SearchUser provide() {
    final UserContext userContext = serviceLocator.getService(UserContext.class);
    final SecurityContext securityContext = serviceLocator.getService(SecurityContext.class);
    return new SearchUser(userContext.getUser(), (permission) -> this.isPermitted(securityContext, permission), (permission, instanceId) -> this.isPermitted(securityContext, permission, instanceId), permittedStreams);
}
Also used : UserContext(org.graylog.security.UserContext) SecurityContext(javax.ws.rs.core.SecurityContext) SearchUser(org.graylog.plugins.views.search.permissions.SearchUser)

Aggregations

SecurityContext (javax.ws.rs.core.SecurityContext)77 Response (javax.ws.rs.core.Response)30 Context (javax.ws.rs.core.Context)18 Test (org.junit.Test)18 List (java.util.List)17 Principal (java.security.Principal)16 LoggerFactory (org.slf4j.LoggerFactory)16 Logger (org.slf4j.Logger)12 ArrayList (java.util.ArrayList)11 Collectors (java.util.stream.Collectors)11 Path (javax.ws.rs.Path)11 IOException (java.io.IOException)10 POST (javax.ws.rs.POST)8 LocalPasswordHandler (com.emc.storageos.systemservices.impl.util.LocalPasswordHandler)6 GET (javax.ws.rs.GET)6 PathParam (javax.ws.rs.PathParam)6 Produces (javax.ws.rs.Produces)6 MediaType (javax.ws.rs.core.MediaType)6 Status (javax.ws.rs.core.Response.Status)6 UriInfo (javax.ws.rs.core.UriInfo)6