Search in sources :

Example 6 with AuthorizationGrant

use of org.gluu.oxauth.model.common.AuthorizationGrant in project oxAuth by GluuFederation.

the class UmaResourceRegistrationWS method deleteResource.

@DELETE
@Path("{rsid}")
public Response deleteResource(@HeaderParam("Authorization") String authorization, @PathParam("rsid") String rsid) {
    try {
        log.debug("Deleting resource descriptions'");
        final AuthorizationGrant authorizationGrant = umaValidationService.assertHasProtectionScope(authorization);
        umaValidationService.validateRestrictedByClient(authorizationGrant.getClientDn(), rsid);
        resourceService.remove(rsid);
        return Response.status(Response.Status.NO_CONTENT).build();
    } catch (Exception ex) {
        log.error("Error on DELETE Resource - " + ex.getMessage(), ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }
        throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, ex.getMessage());
    }
}
Also used : AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant) IOException(java.io.IOException)

Example 7 with AuthorizationGrant

use of org.gluu.oxauth.model.common.AuthorizationGrant in project oxAuth by GluuFederation.

the class StatWS method validateAuthorization.

private void validateAuthorization(String authorization) {
    log.trace("Validating authorization: " + authorization);
    AuthorizationGrant grant = tokenService.getAuthorizationGrant(authorization);
    if (grant == null) {
        log.trace("Unable to find token by authorization: " + authorization);
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Can't find grant for authorization.");
    }
    final AbstractToken accessToken = grant.getAccessToken(tokenService.getToken(authorization));
    if (accessToken == null) {
        log.trace("Unable to find token by authorization: " + authorization);
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Can't find access token.");
    }
    if (accessToken.isExpired()) {
        log.trace("Access Token is expired: " + accessToken.getCode());
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Token expired.");
    }
    if (!grant.getScopesAsString().contains(appConfiguration.getStatAuthorizationScope())) {
        log.trace("Access Token does NOT have '" + appConfiguration.getStatAuthorizationScope() + "' scope which is required to call Statistic Endpoint.");
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, appConfiguration.getStatAuthorizationScope() + " scope is required for token.");
    }
}
Also used : AbstractToken(org.gluu.oxauth.model.common.AbstractToken) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 8 with AuthorizationGrant

use of org.gluu.oxauth.model.common.AuthorizationGrant in project oxAuth by GluuFederation.

the class RevokeRestWebServiceImpl method requestAccessToken.

@Override
public Response requestAccessToken(String token, String tokenTypeHint, String clientId, HttpServletRequest request, HttpServletResponse response, SecurityContext sec) {
    log.debug("Attempting to revoke token: token = {}, tokenTypeHint = {}, isSecure = {}", token, tokenTypeHint, sec.isSecure());
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REVOCATION);
    validateToken(token);
    Response.ResponseBuilder builder = Response.ok();
    SessionClient sessionClient = identity.getSessionClient();
    Client client = sessionClient != null ? sessionClient.getClient() : null;
    if (client == null) {
        client = clientService.getClient(clientId);
        if (!clientService.isPublic(client)) {
            log.trace("Client is not public and not authenticated. Skip revoking.");
            return response(builder, oAuth2AuditLog);
        }
    }
    if (client == null) {
        log.trace("Client is not unknown. Skip revoking.");
        return response(builder, oAuth2AuditLog);
    }
    oAuth2AuditLog.setClientId(client.getClientId());
    TokenTypeHint tth = TokenTypeHint.getByValue(tokenTypeHint);
    AuthorizationGrant authorizationGrant = null;
    if (tth == TokenTypeHint.ACCESS_TOKEN) {
        authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(token);
    } else if (tth == TokenTypeHint.REFRESH_TOKEN) {
        authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), token);
    } else {
        // Since the hint about the type of the token submitted for revocation is optional. oxAuth will
        // search it as Access Token then as Refresh Token.
        authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(token);
        if (authorizationGrant == null) {
            authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), token);
        }
    }
    if (authorizationGrant == null) {
        log.trace("Unable to find token.");
        return response(builder, oAuth2AuditLog);
    }
    if (!authorizationGrant.getClientId().equals(client.getClientId())) {
        log.trace("Token was issued with client {} but revoke is requested with client {}. Skip revoking.", authorizationGrant.getClientId(), client.getClientId());
        return response(builder, oAuth2AuditLog);
    }
    RevokeTokenContext revokeTokenContext = new RevokeTokenContext(request, client, authorizationGrant, builder);
    final boolean scriptResult = externalRevokeTokenService.revokeTokenMethods(revokeTokenContext);
    if (!scriptResult) {
        log.trace("Revoke is forbidden by 'Revoke Token' custom script (method returned false). Exit without revoking.");
        return response(builder, oAuth2AuditLog);
    }
    grantService.removeAllByGrantId(authorizationGrant.getGrantId());
    log.trace("Revoked successfully.");
    return response(builder, oAuth2AuditLog);
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) SessionClient(org.gluu.oxauth.model.session.SessionClient) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) RevokeTokenContext(org.gluu.oxauth.service.external.context.RevokeTokenContext) TokenTypeHint(org.gluu.oxauth.model.common.TokenTypeHint) SessionClient(org.gluu.oxauth.model.session.SessionClient) Client(org.gluu.oxauth.model.registration.Client) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 9 with AuthorizationGrant

use of org.gluu.oxauth.model.common.AuthorizationGrant in project oxAuth by GluuFederation.

the class LogoutAction method processExternalAuthenticatorLogOut.

private ExternalLogoutResult processExternalAuthenticatorLogOut(SessionId sessionId) {
    if ((sessionId != null) && sessionId.getSessionAttributes().containsKey(EXTERNAL_LOGOUT)) {
        log.debug("Detected callback from external system. Resuming logout.");
        return ExternalLogoutResult.SUCCESS;
    }
    AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
    if (authorizationGrant == null) {
        Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
        if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
            authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
        }
    }
    if ((authorizationGrant == null) && (sessionId == null)) {
        return ExternalLogoutResult.FAILURE;
    }
    String acrValues;
    if (authorizationGrant == null) {
        acrValues = sessionIdService.getAcr(sessionId);
    } else {
        acrValues = authorizationGrant.getAcrValues();
    }
    boolean isExternalAuthenticatorLogoutPresent = StringHelper.isNotEmpty(acrValues);
    if (isExternalAuthenticatorLogoutPresent) {
        log.debug("Attemptinmg to execute logout method of '{}' external authenticator.", acrValues);
        CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfigurationByName(acrValues);
        if (customScriptConfiguration == null) {
            log.error("Failed to get ExternalAuthenticatorConfiguration. acr_values: {}", acrValues);
            return ExternalLogoutResult.FAILURE;
        } else {
            boolean scriptExternalLogoutResult = externalAuthenticationService.executeExternalLogout(customScriptConfiguration, null);
            ExternalLogoutResult externalLogoutResult = scriptExternalLogoutResult ? ExternalLogoutResult.SUCCESS : ExternalLogoutResult.FAILURE;
            log.debug("Logout result is '{}' for session '{}', userDn: '{}'", externalLogoutResult, sessionId.getId(), sessionId.getUserDn());
            int apiVersion = externalAuthenticationService.executeExternalGetApiVersion(customScriptConfiguration);
            if (apiVersion < 3) {
                // Not support redirect to external system at logout
                return externalLogoutResult;
            }
            log.trace("According to API version script supports logout redirects");
            String logoutExternalUrl = externalAuthenticationService.getLogoutExternalUrl(customScriptConfiguration, null);
            log.debug("External logout result is '{}' for user '{}'", logoutExternalUrl, sessionId.getUserDn());
            if (StringHelper.isEmpty(logoutExternalUrl)) {
                return externalLogoutResult;
            }
            // Store in session parameters needed to call end_session
            try {
                storeLogoutParametersInSession(sessionId);
            } catch (IOException ex) {
                log.debug("Failed to persist logout parameters in session", ex);
                return ExternalLogoutResult.FAILURE;
            }
            // Redirect to external URL
            facesService.redirectToExternalURL(logoutExternalUrl);
            return ExternalLogoutResult.REDIRECT;
        }
    } else {
        return ExternalLogoutResult.SUCCESS;
    }
}
Also used : IOException(java.io.IOException) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant) CustomScriptConfiguration(org.gluu.model.custom.script.conf.CustomScriptConfiguration)

Example 10 with AuthorizationGrant

use of org.gluu.oxauth.model.common.AuthorizationGrant in project oxAuth by GluuFederation.

the class ClientInfoRestWebServiceImpl method requestClientInfo.

public Response requestClientInfo(String accessToken, String authorization, SecurityContext securityContext) {
    if (tokenService.isBearerAuthToken(authorization)) {
        accessToken = tokenService.getBearerToken(authorization);
    }
    log.debug("Attempting to request Client Info, Access token = {}, Is Secure = {}", new Object[] { accessToken, securityContext.isSecure() });
    Response.ResponseBuilder builder = Response.ok();
    if (!ClientInfoParamsValidator.validateParams(accessToken)) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.errorAsJson(ClientInfoErrorResponseType.INVALID_REQUEST, "Failed to validate access token."));
    } else {
        AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
        if (authorizationGrant == null) {
            log.trace("Failed to find authorization grant for access token.");
            return Response.status(400).entity(errorResponseFactory.getErrorAsJson(ClientInfoErrorResponseType.INVALID_TOKEN, "", "Unable to find grant object associated with access token.")).build();
        }
        final AbstractToken token = authorizationGrant.getAccessToken(accessToken);
        if (token == null || !token.isValid()) {
            log.trace("Invalid access token.");
            return Response.status(400).entity(errorResponseFactory.getErrorAsJson(ClientInfoErrorResponseType.INVALID_TOKEN, "", "Invalid access token.")).build();
        }
        builder.cacheControl(ServerUtil.cacheControlWithNoStoreTransformAndPrivate());
        builder.header("Pragma", "no-cache");
        builder.entity(getJSonResponse(authorizationGrant.getClient(), authorizationGrant.getScopes()));
    }
    return builder.build();
}
Also used : Response(javax.ws.rs.core.Response) AbstractToken(org.gluu.oxauth.model.common.AbstractToken) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Aggregations

AuthorizationGrant (org.gluu.oxauth.model.common.AuthorizationGrant)20 IOException (java.io.IOException)6 WebApplicationException (javax.ws.rs.WebApplicationException)5 AbstractToken (org.gluu.oxauth.model.common.AbstractToken)5 SessionId (org.gluu.oxauth.model.common.SessionId)4 Response (javax.ws.rs.core.Response)3 OAuth2AuditLog (org.gluu.oxauth.model.audit.OAuth2AuditLog)3 InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)3 Client (org.gluu.oxauth.model.registration.Client)3 URISyntaxException (java.net.URISyntaxException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Pair (org.gluu.util.Pair)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)1 CustomScriptConfiguration (org.gluu.model.custom.script.conf.CustomScriptConfiguration)1 AccessToken (org.gluu.oxauth.model.common.AccessToken)1 IntrospectionResponse (org.gluu.oxauth.model.common.IntrospectionResponse)1 TokenTypeHint (org.gluu.oxauth.model.common.TokenTypeHint)1 User (org.gluu.oxauth.model.common.User)1