org.gluu.util.Pair Java Examples

The following examples show how to use org.gluu.util.Pair. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EndSessionRestWebServiceImpl.java    From oxAuth with MIT License 6 votes vote down vote up
private Response httpBased(Set<String> frontchannelUris, String postLogoutRedirectUri, String state, Pair<SessionId, AuthorizationGrant> pair, HttpServletRequest httpRequest) {
    try {
        final EndSessionContext context = new EndSessionContext(httpRequest, frontchannelUris, postLogoutRedirectUri, pair.getFirst());
        final String htmlFromScript = externalEndSessionService.getFrontchannelHtml(context);
        if (StringUtils.isNotBlank(htmlFromScript)) {
            log.debug("HTML from `getFrontchannelHtml` external script: " + htmlFromScript);
            return okResponse(htmlFromScript);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    // default handling
    final String html = EndSessionUtils.createFronthannelHtml(frontchannelUris, postLogoutRedirectUri, state);
    log.debug("Constructed html logout page: " + html);
    return okResponse(html);
}
 
Example #2
Source File: EndSessionRestWebServiceImpl.java    From oxAuth with MIT License 6 votes vote down vote up
private Pair<SessionId, AuthorizationGrant> getPair(String idTokenHint, String sessionId, HttpServletRequest httpRequest) {
    AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
    if (authorizationGrant == null) {
        Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
        if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
            authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
        }
    }

    SessionId ldapSessionId = null;

    try {
        String id = sessionId;
        if (StringHelper.isEmpty(id)) {
            id = cookieService.getSessionIdFromCookie(httpRequest);
        }
        if (StringHelper.isNotEmpty(id)) {
            ldapSessionId = sessionIdService.getSessionId(id);
        }
    } catch (Exception e) {
        log.error("Failed to current session id.", e);
    }
    return new Pair<>(ldapSessionId, authorizationGrant);
}
 
Example #3
Source File: EndSessionRestWebServiceImpl.java    From oxAuth with MIT License 6 votes vote down vote up
private Set<Client> getSsoClients(Pair<SessionId, AuthorizationGrant> pair) {
    SessionId sessionId = pair.getFirst();
    AuthorizationGrant authorizationGrant = pair.getSecond();
    if (sessionId == null) {
        log.error("session_id is not passed to endpoint (as cookie or manually). Therefore unable to match clients for session_id.");
        return Sets.newHashSet();
    }

    final Set<Client> clients = sessionId.getPermissionGrantedMap() != null ?
            clientService.getClient(sessionId.getPermissionGrantedMap().getClientIds(true), true) :
            Sets.newHashSet();
    if (authorizationGrant != null) {
        clients.add(authorizationGrant.getClient());
    }
    return clients;
}
 
Example #4
Source File: EndSessionRestWebServiceImpl.java    From oxAuth with MIT License 6 votes vote down vote up
private void auditLogging(HttpServletRequest request, Pair<SessionId, AuthorizationGrant> pair) {
    SessionId sessionId = pair.getFirst();
    AuthorizationGrant authorizationGrant = pair.getSecond();

    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.SESSION_DESTROYED);
    oAuth2AuditLog.setSuccess(true);

    if (authorizationGrant != null) {
        oAuth2AuditLog.setClientId(authorizationGrant.getClientId());
        oAuth2AuditLog.setScope(StringUtils.join(authorizationGrant.getScopes(), " "));
        oAuth2AuditLog.setUsername(authorizationGrant.getUserId());
    } else if (sessionId != null) {
        oAuth2AuditLog.setClientId(sessionId.getPermissionGrantedMap().getClientIds(true).toString());
        oAuth2AuditLog.setScope(sessionId.getSessionAttributes().get(AuthorizeRequestParam.SCOPE));
        oAuth2AuditLog.setUsername(sessionId.getUserDn());
    }

    applicationAuditLogger.sendMessage(oAuth2AuditLog);
}
 
Example #5
Source File: RequestParameterService.java    From oxAuth with MIT License 6 votes vote down vote up
public Pair<String, String> getParameterValueWithType(String p_name) {
    String value = null;
    String clazz = null;
    final Object o = identity.getWorkingParameter(p_name);
    if (o instanceof String) {
        final String s = (String) o;
        value = s;
        clazz = String.class.getName();
    } else if (o instanceof Integer) {
        final Integer i = (Integer) o;
        value = i.toString();
        clazz = Integer.class.getName();
    } else if (o instanceof Boolean) {
        final Boolean b = (Boolean) o;
        value = b.toString();
        clazz = Boolean.class.getName();
    }

    return new Pair<String, String>(value, clazz);
}
 
Example #6
Source File: PublicOpKeyService.java    From oxd with Apache License 2.0 6 votes vote down vote up
public PublicKey getPublicKey(String jwkSetUrl, String keyId) {
    try {
        PublicKey publicKey = null;

        final Pair<String, String> mapKey = new Pair<>(jwkSetUrl, keyId);

        PublicKey cachedKey = cache.getIfPresent(mapKey);
        if (cachedKey != null) {
            LOG.debug("Taken public key from cache, mapKey: " + mapKey);
            return cachedKey;
        }

        JwkClient jwkClient = opClientFactory.createJwkClient(jwkSetUrl);
        jwkClient.setExecutor(new ApacheHttpClient4Executor(httpService.getHttpClient()));

        JwkResponse jwkResponse = jwkClient.exec();
        if (jwkResponse != null && jwkResponse.getStatus() == 200) {
            publicKey = jwkResponse.getPublicKey(keyId);
        }

        return publicKey;
    } catch (Exception e) {
        LOG.error("Failed to fetch public key.", e);
        throw new RuntimeException("Failed to fetch public key.", e);
    }
}
 
Example #7
Source File: AuthenticationService.java    From oxAuth with MIT License 6 votes vote down vote up
private Pair<Boolean, User> localAuthenticate(String nameValue, String password, String ... nameAttributes) {
	User user = userService.getUserByAttributes(nameValue, nameAttributes, new String[] {"uid", "gluuStatus"});
	if (user != null) {
		if (!checkUserStatus(user)) {
			return new Pair<Boolean, User>(false, user);
		}

		// Use local LDAP server for user authentication
		boolean authenticated = ldapEntryManager.authenticate(user.getDn(), password);
		if (authenticated) {
			configureAuthenticatedUser(user);
			updateLastLogonUserTime(user);

			log.trace("Authenticate: credentials: '{}', credentials.userName: '{}', authenticatedUser.userId: '{}'",
					System.identityHashCode(credentials), credentials.getUsername(), getAuthenticatedUserId());
		}

		return new Pair<Boolean, User>(authenticated, user);
	}

	return new Pair<Boolean, User>(false, null);
}
 
Example #8
Source File: BaseUmaProtectionService.java    From oxTrust with MIT License 5 votes vote down vote up
Response processUmaAuthorization(String authorization, ResourceInfo resourceInfo) throws Exception {
	List<String> scopes = getRequestedScopes(resourceInfo);
	Token patToken = null;
	try {
		patToken = getPatToken();
	} catch (UmaProtectionException ex) {
		return getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Failed to obtain PAT token");
	}

	Pair<Boolean, Response> rptTokenValidationResult;
	if (!scopes.isEmpty()) {
		rptTokenValidationResult = umaPermissionService.validateRptToken(patToken, authorization,
				getUmaResourceId(), scopes);
	} else {
		rptTokenValidationResult = umaPermissionService.validateRptToken(patToken, authorization,
				getUmaResourceId(), getUmaScope());
	}

	if (rptTokenValidationResult.getFirst()) {
		if (rptTokenValidationResult.getSecond() != null) {
			return rptTokenValidationResult.getSecond();
		}
	} else {
		return getErrorResponse(Response.Status.UNAUTHORIZED, "Invalid GAT/RPT token");
	}
	return null;

}
 
Example #9
Source File: EndSessionRestWebServiceImpl.java    From oxAuth with MIT License 5 votes vote down vote up
private String validatePostLogoutRedirectUri(String postLogoutRedirectUri, Pair<SessionId, AuthorizationGrant> pair) {
    try {
        if (StringUtils.isBlank(postLogoutRedirectUri)) {
            return "";
        }
        if (appConfiguration.getAllowPostLogoutRedirectWithoutValidation()) {
            log.trace("Skipped post_logout_redirect_uri validation (because allowPostLogoutRedirectWithoutValidation=true)");
            return postLogoutRedirectUri;
        }

        final String result;
        if (pair.getSecond() == null) {
            result = redirectionUriService.validatePostLogoutRedirectUri(pair.getFirst(), postLogoutRedirectUri);
        } else {
            result = redirectionUriService.validatePostLogoutRedirectUri(pair.getSecond().getClient().getClientId(), postLogoutRedirectUri);
        }

        if (StringUtils.isBlank(result)) {
            log.trace("Failed to validate post_logout_redirect_uri.");
            throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
        }

        if (StringUtils.isNotBlank(result)) {
            return result;
        }
        log.trace("Unable to validate post_logout_redirect_uri.");
        throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
    } catch (WebApplicationException e) {
        if (pair.getFirst() != null) {
            log.error(e.getMessage(), e);
            throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
        } else {
            throw e;
        }
    }
}
 
Example #10
Source File: EndSessionRestWebServiceImpl.java    From oxAuth with MIT License 5 votes vote down vote up
private void endSession(Pair<SessionId, AuthorizationGrant> pair, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    // Clean up authorization session
    removeConsentSessionId(httpRequest, httpResponse);

    removeSessionId(pair, httpResponse);

    boolean isExternalLogoutPresent;
    boolean externalLogoutResult = false;

    isExternalLogoutPresent = externalApplicationSessionService.isEnabled();
    if (isExternalLogoutPresent) {
        String userName = pair.getFirst().getSessionAttributes().get(Constants.AUTHENTICATED_USER);
        externalLogoutResult = externalApplicationSessionService.executeExternalEndSessionMethods(httpRequest, pair.getFirst());
        log.info("End session result for '{}': '{}'", userName, "logout", externalLogoutResult);
    }

    boolean isGrantAndExternalLogoutSuccessful = isExternalLogoutPresent && externalLogoutResult;
    if (isExternalLogoutPresent && !isGrantAndExternalLogoutSuccessful) {
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, EndSessionErrorResponseType.INVALID_GRANT, "External logout is present but executed external logout script returned failed result.");
    }

    grantService.logout(pair.getFirst().getDn());

    if (identity != null) {
        identity.logout();
    }
}
 
Example #11
Source File: EndSessionRestWebServiceImpl.java    From oxAuth with MIT License 5 votes vote down vote up
private void removeSessionId(Pair<SessionId, AuthorizationGrant> pair, HttpServletResponse httpResponse) {
    try {
        boolean result = sessionIdService.remove(pair.getFirst());
        if (!result) {
            log.error("Failed to remove session_id '{}'", pair.getFirst().getId());
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        cookieService.removeSessionIdCookie(httpResponse);
        cookieService.removeOPBrowserStateCookie(httpResponse);
    }
}
 
Example #12
Source File: RequestParameterService.java    From oxAuth with MIT License 5 votes vote down vote up
public String getParameterValue(String p_name) {
    Pair<String, String> valueWithType = getParameterValueWithType(p_name);
    if (valueWithType == null) {
        return null;
    }

    return valueWithType.getFirst();
}
 
Example #13
Source File: AuthenticationService.java    From oxAuth with MIT License 5 votes vote down vote up
public void updateExtraParameters(Map<String, String> sessionIdAttributes, List<String> extraParameters) {
    // Load extra parameters set
    Map<String, String> authExternalAttributes = getExternalScriptExtraParameters(sessionIdAttributes);

    if (extraParameters != null) {
    	log.trace("Attempting to store extraParameters: {}", extraParameters);
        for (String extraParameter : extraParameters) {
            if (isParameterExists(extraParameter)) {
                Pair<String, String> extraParameterValueWithType = requestParameterService
                        .getParameterValueWithType(extraParameter);
                String extraParameterValue = extraParameterValueWithType.getFirst();
                String extraParameterType = extraParameterValueWithType.getSecond();

                // Store parameter name and value
                sessionIdAttributes.put(extraParameter, extraParameterValue);

                // Store parameter name and type
                authExternalAttributes.put(extraParameter, extraParameterType);
            }
        }
    }

    // Store identity working parameters in session
    setExternalScriptExtraParameters(sessionIdAttributes, authExternalAttributes);
	log.trace("Storing sessionIdAttributes: {}", sessionIdAttributes);
	log.trace("Storing authExternalAttributes: {}", authExternalAttributes);
}
 
Example #14
Source File: PublicOpKeyService.java    From oxd with Apache License 2.0 4 votes vote down vote up
public PublicKey refetchKey(String jwkUrl, String kid) {
    cache.invalidate(new Pair<>(jwkUrl, kid));
    return getPublicKey(jwkUrl, kid);
}
 
Example #15
Source File: UmaPermissionService.java    From oxTrust with MIT License 4 votes vote down vote up
public Pair<Boolean, Response> validateRptToken(Token patToken, String authorization, String umaResourceId,
		String scopeId) {
	return validateRptToken(patToken, authorization, umaResourceId, Arrays.asList(scopeId));
}
 
Example #16
Source File: IntrospectionWebService.java    From oxAuth with MIT License 4 votes vote down vote up
/**
 * @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)) {
        
        String encodedCredentials = tokenService.getBasicToken(authorization);

        String token = new String(Base64.decodeBase64(encodedCredentials), Util.UTF8_STRING_ENCODING);

        int delim = token.indexOf(":");

        if (delim != -1) {
            String clientId = URLDecoder.decode(token.substring(0, delim), Util.UTF8_STRING_ENCODING);
            String password = URLDecoder.decode(token.substring(delim + 1), Util.UTF8_STRING_ENCODING);
            if (clientService.authenticate(clientId, password)) {
                grant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
                if (grant != null && !grant.getClientId().equals(clientId)) {
                    log.trace("Failed to match grant object clientId and client id provided during authentication.");
                    return EMPTY;
                }
                return new Pair<>(grant, true);
            } else {
                log.trace("Failed to perform basic authentication for client: " + clientId);
            }
        }
    }
    return EMPTY;
}
 
Example #17
Source File: IntrospectionWebService.java    From oxAuth with MIT License 4 votes vote down vote up
private Response introspect(String p_authorization, String p_token, String tokenTypeHint, String responseAsJwt, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        log.trace("Introspect token, authorization: {}, token to introsppect: {}, tokenTypeHint:", p_authorization, p_token, tokenTypeHint);
        if (StringUtils.isBlank(p_authorization) || StringUtils.isBlank(p_token)) {
            log.trace("Bad request: Authorization header or token is blank.");
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, "")).build();
        }

        final Pair<AuthorizationGrant, Boolean> pair = getAuthorizationGrant(p_authorization, p_token);
        final AuthorizationGrant authorizationGrant = pair.getFirst();
        if (authorizationGrant == null) {
            log.error("Authorization grant is null.");
            return 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(p_authorization));

        if ((authorizationAccessToken == null || !authorizationAccessToken.isValid()) && !pair.getSecond()) {
            log.error("Access token is not valid. Valid: " + (authorizationAccessToken != null && authorizationAccessToken.isValid()) + ", basicClientAuthentication: " + pair.getSecond());
            return Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.ACCESS_DENIED, "Access token is not valid")).build();
        }

        if (ServerUtil.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);
            return Response.status(Response.Status.UNAUTHORIZED).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.ACCESS_DENIED, reason)).type(MediaType.APPLICATION_JSON_TYPE).build();
        }

        final IntrospectionResponse response = new IntrospectionResponse(false);

        final AuthorizationGrant grantOfIntrospectionToken = authorizationGrantList.getAuthorizationGrantByAccessToken(p_token);

        AbstractToken tokenToIntrospect = null;
        if (grantOfIntrospectionToken != null) {
            tokenToIntrospect = grantOfIntrospectionToken.getAccessToken(p_token);

            response.setActive(tokenToIntrospect.isValid());
            response.setExpiresAt(ServerUtil.dateToSeconds(tokenToIntrospect.getExpirationDate()));
            response.setIssuedAt(ServerUtil.dateToSeconds(tokenToIntrospect.getCreationDate()));
            response.setAcrValues(grantOfIntrospectionToken.getAcrValues());
            response.setScope(grantOfIntrospectionToken.getScopes() != null ? grantOfIntrospectionToken.getScopes() : Lists.newArrayList()); // #433
            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() : TokenType.BEARER.getName());
            }
        } else {
            log.debug("Failed to find grant for access_token: " + p_token + ". Return 200 with active=false.");
        }
        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 extenal introspection scripts.");
        } else {
            responseAsJsonObject = createResponseAsJsonObject(response, tokenToIntrospect);
            log.trace("Canceled changes made by external introspection script since method returned `false`.");
        }

        if (Boolean.TRUE.toString().equalsIgnoreCase(responseAsJwt)) {
            return Response.status(Response.Status.OK).entity(createResponseAsJwt(responseAsJsonObject, authorizationGrant)).build();
        }

        return Response.status(Response.Status.OK).entity(responseAsJsonObject.toString()).type(MediaType.APPLICATION_JSON_TYPE).build();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON_TYPE).build();
    }
}
 
Example #18
Source File: AuthenticationService.java    From oxAuth with MIT License 4 votes vote down vote up
/**
 * Authenticate user.
 *
 * @param nameValue
 *            The name value to find user
 * @param password
 *            The user's password.
 * @param nameAttributes
 *            List of attribute to search.
 * @return <code>true</code> if success, otherwise <code>false</code>.
 */
public boolean authenticate(String nameValue, String password, String ... nameAttributes) {
	log.debug("Authenticating user with LDAP: nameValue: '{}', nameAttributes: '{}', credentials: '{}'", nameValue,
			ArrayHelper.toString(nameAttributes),
			System.identityHashCode(credentials));

	Pair<Boolean, User> authenticatedPair = null;
	boolean authenticated = false;
	boolean protectionServiceEnabled = authenticationProtectionService.isEnabled();

	com.codahale.metrics.Timer.Context timerContext = metricService
			.getTimer(MetricType.OXAUTH_USER_AUTHENTICATION_RATE).time();
	try {
		authenticatedPair = localAuthenticate(nameValue, password, nameAttributes);
	} finally {
		timerContext.stop();
	}

	String userId = null;
	if ((authenticatedPair != null) && (authenticatedPair.getSecond() != null)) {
		authenticated = authenticatedPair.getFirst();
		userId = authenticatedPair.getSecond().getUserId();
	}
	setAuthenticatedUserSessionAttribute(userId, authenticated);

	MetricType metricType;
	if (authenticated) {
		metricType = MetricType.OXAUTH_USER_AUTHENTICATION_SUCCESS;
	} else {
		metricType = MetricType.OXAUTH_USER_AUTHENTICATION_FAILURES;
	}

	metricService.incCounter(metricType);

	if (protectionServiceEnabled) {
		authenticationProtectionService.storeAttempt(userId, authenticated);
		authenticationProtectionService.doDelayIfNeeded(userId);
	}

	return authenticated;
}
 
Example #19
Source File: UmaPermissionService.java    From oxTrust with MIT License 4 votes vote down vote up
public Pair<Boolean, Response> validateRptToken(Token patToken, String authorization, String resourceId,
		List<String> scopeIds) {
	/*
	 * //caller of this method never pass null patToken if (patToken == null) {
	 * return authenticationFailure; }
	 */
	log.trace("Validating RPT, resourceId: {}, scopeIds: {}, authorization: {}", resourceId, scopeIds,
			authorization);

	if (StringHelper.isNotEmpty(authorization) && authorization.startsWith("Bearer ")) {
		String rptToken = authorization.substring(7);

		RptIntrospectionResponse rptStatusResponse = getStatusResponse(patToken, rptToken);
		log.trace("RPT status response: {} ", rptStatusResponse);
		if ((rptStatusResponse == null) || !rptStatusResponse.getActive()) {
			log.error("Status response for RPT token: '{}' is invalid", rptToken);
			// return authenticationFailure;
		} else {
			boolean rptHasPermissions = isRptHasPermissions(rptStatusResponse);

			if (rptHasPermissions) {
				// Collect all scopes
				List<String> returnScopeIds = new LinkedList<String>();
				for (UmaPermission umaPermission : rptStatusResponse.getPermissions()) {
					if (umaPermission.getScopes() != null) {
						returnScopeIds.addAll(umaPermission.getScopes());
					}
				}

				if (returnScopeIds.containsAll(scopeIds)) {
					return authenticationSuccess;
				}

				log.error("Status response for RPT token: '{}' not contains right permissions", rptToken);
			}
		}
	}

	Response registerPermissionsResponse = prepareRegisterPermissionsResponse(patToken, resourceId, scopeIds);
	if (registerPermissionsResponse == null) {
		return authenticationFailure;
	}

	return new Pair<Boolean, Response>(true, registerPermissionsResponse);
}