Search in sources :

Example 21 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class RedirectionUriService method validatePostLogoutRedirectUri.

public String validatePostLogoutRedirectUri(SessionId sessionId, String postLogoutRedirectUri) {
    if (sessionId == null) {
        throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, EndSessionErrorResponseType.SESSION_NOT_PASSED, "Session object is not found.");
    }
    if (Strings.isNullOrEmpty(postLogoutRedirectUri)) {
        throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_PASSED, "`post_logout_redirect_uri` is empty.");
    }
    final Set<Client> clientsByDns = sessionId.getPermissionGrantedMap() != null ? clientService.getClient(sessionId.getPermissionGrantedMap().getClientIds(true), true) : Sets.<Client>newHashSet();
    log.trace("Validating post logout redirect URI: postLogoutRedirectUri = {}", postLogoutRedirectUri);
    for (Client client : clientsByDns) {
        String[] postLogoutRedirectUris = client.getPostLogoutRedirectUris();
        String validatedUri = validatePostLogoutRedirectUri(postLogoutRedirectUri, postLogoutRedirectUris);
        if (StringUtils.isNotBlank(validatedUri)) {
            return validatedUri;
        }
    }
    throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, "Unable to validate `post_logout_redirect_uri`");
}
Also used : Client(org.gluu.oxauth.model.registration.Client)

Example 22 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class RegisterRestWebServiceImpl method delete.

@Override
public Response delete(String clientId, String authorization, HttpServletRequest httpRequest, SecurityContext securityContext) {
    try {
        String accessToken = tokenService.getToken(authorization);
        log.debug("Attempting to delete client: clientId = {0}, registrationAccessToken = {1} isSecure = {2}", clientId, accessToken, securityContext.isSecure());
        if (!appConfiguration.getDynamicRegistrationEnabled()) {
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Dynamic registration is disabled.");
        }
        if (!registerParamsValidator.validateParamsClientRead(clientId, accessToken)) {
            log.trace("Client parameters are invalid.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "");
        }
        Client client = clientService.getClient(clientId, accessToken);
        if (client == null) {
            throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, RegisterErrorResponseType.INVALID_TOKEN, "");
        }
        clientService.remove(client);
        return Response.status(Response.Status.NO_CONTENT).cacheControl(ServerUtil.cacheControl(true, false)).header("Pragma", "no-cache").build();
    } catch (WebApplicationException e) {
        if (e.getResponse() != null) {
            return e.getResponse();
        }
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Failed to process request.");
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Client(org.gluu.oxauth.model.registration.Client) JSONException(org.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException)

Example 23 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class RegisterRestWebServiceImpl method requestClientRead.

@Override
public Response requestClientRead(String clientId, String authorization, HttpServletRequest httpRequest, SecurityContext securityContext) {
    String accessToken = tokenService.getToken(authorization);
    log.debug("Attempting to read client: clientId = {}, registrationAccessToken = {} isSecure = {}", clientId, accessToken, securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_READ);
    oAuth2AuditLog.setClientId(clientId);
    try {
        if (appConfiguration.getDynamicRegistrationEnabled()) {
            if (registerParamsValidator.validateParamsClientRead(clientId, accessToken)) {
                Client client = clientService.getClient(clientId, accessToken);
                if (client != null) {
                    oAuth2AuditLog.setScope(clientScopesToString(client));
                    oAuth2AuditLog.setSuccess(true);
                    builder.entity(clientAsEntity(client));
                } else {
                    log.trace("The Access Token is not valid for the Client ID, returns invalid_token error.");
                    builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()).type(MediaType.APPLICATION_JSON_TYPE);
                    builder.entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_TOKEN, "The Access Token is not valid for the Client"));
                }
            } else {
                log.trace("Client ID or Access Token is not valid.");
                throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Client ID or Access Token is not valid.");
            }
        } else {
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Dynamic registration is disabled.");
        }
    } catch (JSONException e) {
        log.error(e.getMessage(), e);
        throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Failed to parse json.");
    } catch (StringEncrypter.EncryptionException e) {
        log.error(e.getMessage(), e);
        throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Encryption exception occurred.");
    }
    builder.cacheControl(ServerUtil.cacheControl(true, false));
    builder.header("Pragma", "no-cache");
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : Response(javax.ws.rs.core.Response) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) JSONException(org.json.JSONException) Client(org.gluu.oxauth.model.registration.Client) StringEncrypter(org.gluu.util.security.StringEncrypter)

Example 24 with Client

use of org.gluu.oxauth.model.registration.Client 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 25 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class ClientAuthorizationsService method add.

public void add(String userInum, String clientId, Set<String> scopes) {
    log.trace("Attempting to add client authorization, scopes:" + scopes + ", clientId: " + clientId + ", userInum: " + userInum);
    Client client = clientService.getClient(clientId);
    // oxAuth #441 Pre-Authorization + Persist Authorizations... don't write anything
    // If a client has pre-authorization=true, there is no point to create the entry under
    // ou=clientAuthorizations it will negatively impact performance, grow the size of the
    // ldap database, and serve no purpose.
    prepareBranch();
    ClientAuthorization clientAuthorization = find(userInum, clientId);
    if (clientAuthorization == null) {
        final String id = createId(userInum, clientId);
        clientAuthorization = new ClientAuthorization();
        clientAuthorization.setId(id);
        clientAuthorization.setDn(createDn(id));
        clientAuthorization.setClientId(clientId);
        clientAuthorization.setUserId(userInum);
        clientAuthorization.setScopes(scopes.toArray(new String[scopes.size()]));
        clientAuthorization.setDeletable(!client.getAttributes().getKeepClientAuthorizationAfterExpiration());
        clientAuthorization.setExpirationDate(client.getExpirationDate());
        clientAuthorization.setTtl(appConfiguration.getDynamicRegistrationExpirationTime());
        ldapEntryManager.persist(clientAuthorization);
    } else if (ArrayUtils.isNotEmpty(clientAuthorization.getScopes())) {
        Set<String> set = new HashSet<>(scopes);
        set.addAll(Arrays.asList(clientAuthorization.getScopes()));
        if (set.size() != clientAuthorization.getScopes().length) {
            clientAuthorization.setScopes(set.toArray(new String[set.size()]));
            ldapEntryManager.merge(clientAuthorization);
        }
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ClientAuthorization(org.gluu.oxauth.model.ldap.ClientAuthorization) Client(org.gluu.oxauth.model.registration.Client)

Aggregations

Client (org.gluu.oxauth.model.registration.Client)55 WebApplicationException (javax.ws.rs.WebApplicationException)15 Test (org.testng.annotations.Test)14 BaseComponentTest (org.gluu.oxauth.BaseComponentTest)12 InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)10 OAuth2AuditLog (org.gluu.oxauth.model.audit.OAuth2AuditLog)8 JSONException (org.json.JSONException)8 Response (javax.ws.rs.core.Response)6 EntryPersistenceException (org.gluu.persist.exception.EntryPersistenceException)6 JSONObject (org.json.JSONObject)6 IOException (java.io.IOException)5 Date (java.util.Date)5 Jwt (org.gluu.oxauth.model.jwt.Jwt)5 SessionClient (org.gluu.oxauth.model.session.SessionClient)5 URI (java.net.URI)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 JwtAuthorizationRequest (org.gluu.oxauth.model.authorize.JwtAuthorizationRequest)4 ArrayList (java.util.ArrayList)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 Claim (org.gluu.oxauth.model.authorize.Claim)3