Java Code Examples for org.gluu.util.Pair#getSecond()

The following examples show how to use org.gluu.util.Pair#getSecond() . 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 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 2
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 3
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 4
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 5
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 6
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 7
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();
    }
}