Search in sources :

Example 46 with Client

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

the class EndSessionRestWebServiceImpl method getSsoClients.

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;
}
Also used : Client(org.gluu.oxauth.model.registration.Client) SessionId(org.gluu.oxauth.model.common.SessionId) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 47 with Client

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

the class EndSessionRestWebServiceImpl method requestEndSession.

@Override
public Response requestEndSession(String idTokenHint, String postLogoutRedirectUri, String state, String sessionId, String sid, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext sec) {
    try {
        log.debug("Attempting to end session, idTokenHint: {}, postLogoutRedirectUri: {}, sessionId: {}, sid: {}, Is Secure = {}", idTokenHint, postLogoutRedirectUri, sessionId, sid, sec.isSecure());
        if (StringUtils.isBlank(sid) && StringUtils.isNotBlank(sessionId))
            // backward compatibility. WIll be removed in next major release.
            sid = sessionId;
        Jwt idToken = validateIdTokenHint(idTokenHint, postLogoutRedirectUri);
        validateSidRequestParameter(sid, postLogoutRedirectUri);
        final Pair<SessionId, AuthorizationGrant> pair = getPair(idTokenHint, sid, httpRequest);
        if (pair.getFirst() == null) {
            final String reason = "Failed to identify session by session_id query parameter or by session_id cookie.";
            throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
        }
        postLogoutRedirectUri = validatePostLogoutRedirectUri(postLogoutRedirectUri, pair);
        validateSid(postLogoutRedirectUri, idToken, pair.getFirst());
        endSession(pair, httpRequest, httpResponse);
        auditLogging(httpRequest, pair);
        Set<Client> clients = getSsoClients(pair);
        Set<String> frontchannelUris = Sets.newHashSet();
        Map<String, Client> backchannelUris = Maps.newHashMap();
        for (Client client : clients) {
            boolean hasBackchannel = false;
            for (String logoutUri : client.getAttributes().getBackchannelLogoutUri()) {
                if (Util.isNullOrEmpty(logoutUri)) {
                    // skip if logout_uri is blank
                    continue;
                }
                backchannelUris.put(logoutUri, client);
                hasBackchannel = true;
            }
            if (hasBackchannel) {
                // client has backchannel_logout_uri
                continue;
            }
            for (String logoutUri : client.getFrontChannelLogoutUri()) {
                if (Util.isNullOrEmpty(logoutUri)) {
                    // skip if logout_uri is blank
                    continue;
                }
                if (client.getFrontChannelLogoutSessionRequired()) {
                    logoutUri = EndSessionUtils.appendSid(logoutUri, pair.getFirst().getOutsideSid(), appConfiguration.getIssuer());
                }
                frontchannelUris.add(logoutUri);
            }
        }
        backChannel(backchannelUris, pair.getSecond(), pair.getFirst());
        if (frontchannelUris.isEmpty() && StringUtils.isNotBlank(postLogoutRedirectUri)) {
            // no front-channel
            log.trace("No frontchannel_redirect_uri's found in clients involved in SSO.");
            try {
                log.trace("Redirect to postlogout_redirect_uri: " + postLogoutRedirectUri);
                return Response.status(Response.Status.FOUND).location(new URI(postLogoutRedirectUri)).build();
            } catch (URISyntaxException e) {
                final String message = "Failed to create URI for " + postLogoutRedirectUri + " postlogout_redirect_uri.";
                log.error(message);
                return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(EndSessionErrorResponseType.INVALID_REQUEST, message)).build();
            }
        }
        return httpBased(frontchannelUris, postLogoutRedirectUri, state, pair, httpRequest);
    } catch (WebApplicationException e) {
        if (e.getResponse() != null) {
            return e.getResponse();
        }
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponseFactory.getJsonErrorResponse(GluuErrorResponseType.SERVER_ERROR)).build());
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Jwt(org.gluu.oxauth.model.jwt.Jwt) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) Client(org.gluu.oxauth.model.registration.Client) SessionId(org.gluu.oxauth.model.common.SessionId) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 48 with Client

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

the class UserInfoRestWebServiceImpl method getJSonResponse.

/**
 * Builds a JSon String with the response parameters.
 */
public String getJSonResponse(User user, AuthorizationGrant authorizationGrant, Collection<String> scopes) throws Exception {
    log.trace("Building JSON reponse with next scopes {0} for user {1} and user custom attributes {0}", scopes, user.getUserId(), user.getCustomAttributes());
    JsonWebResponse jsonWebResponse = new JsonWebResponse();
    // Claims
    List<Scope> dynamicScopes = new ArrayList<Scope>();
    for (String scopeName : scopes) {
        org.oxauth.persistence.model.Scope scope = scopeService.getScopeById(scopeName);
        if ((scope != null) && (org.gluu.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType())) {
            dynamicScopes.add(scope);
            continue;
        }
        Map<String, Object> claims = scopeService.getClaims(user, scope);
        if (claims == null) {
            continue;
        }
        if (scope != null && Boolean.TRUE.equals(scope.isOxAuthGroupClaims())) {
            JwtSubClaimObject groupClaim = new JwtSubClaimObject();
            groupClaim.setName(scope.getId());
            for (Map.Entry<String, Object> entry : claims.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof List) {
                    groupClaim.setClaim(key, (List<String>) value);
                } else {
                    groupClaim.setClaim(key, String.valueOf(value));
                }
            }
            jsonWebResponse.getClaims().setClaim(scope.getId(), groupClaim);
        } else {
            for (Map.Entry<String, Object> entry : claims.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof List) {
                    jsonWebResponse.getClaims().setClaim(key, (List<String>) value);
                } else if (value instanceof Boolean) {
                    jsonWebResponse.getClaims().setClaim(key, (Boolean) value);
                } else if (value instanceof Date) {
                    jsonWebResponse.getClaims().setClaim(key, ((Date) value).getTime() / 1000);
                } else {
                    jsonWebResponse.getClaims().setClaim(key, String.valueOf(value));
                }
            }
        }
    }
    if (authorizationGrant.getClaims() != null) {
        JSONObject claimsObj = new JSONObject(authorizationGrant.getClaims());
        if (claimsObj.has("userinfo")) {
            JSONObject userInfoObj = claimsObj.getJSONObject("userinfo");
            for (Iterator<String> it = userInfoObj.keys(); it.hasNext(); ) {
                String claimName = it.next();
                // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType());
                boolean optional = true;
                GluuAttribute gluuAttribute = attributeService.getByClaimName(claimName);
                if (gluuAttribute != null) {
                    String ldapClaimName = gluuAttribute.getName();
                    Object attribute = user.getAttribute(ldapClaimName, optional, gluuAttribute.getOxMultiValuedAttribute());
                    jsonWebResponse.getClaims().setClaimFromJsonObject(claimName, attribute);
                }
            }
        }
    }
    if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember() != null) {
        for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getUserInfoMember().getClaims()) {
            // ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType());
            boolean optional = true;
            GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName());
            if (gluuAttribute != null) {
                Client client = authorizationGrant.getClient();
                if (validateRequesteClaim(gluuAttribute, client.getClaims(), scopes)) {
                    String ldapClaimName = gluuAttribute.getName();
                    Object attribute = user.getAttribute(ldapClaimName, optional, gluuAttribute.getOxMultiValuedAttribute());
                    jsonWebResponse.getClaims().setClaimFromJsonObject(claim.getName(), attribute);
                }
            }
        }
    }
    jsonWebResponse.getClaims().setSubjectIdentifier(authorizationGrant.getSub());
    if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) {
        final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant);
        DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jsonWebResponse, unmodifiableAuthorizationGrant);
        externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext);
    }
    return jsonWebResponse.toString();
}
Also used : JsonWebResponse(org.gluu.oxauth.model.token.JsonWebResponse) DynamicScopeExternalContext(org.gluu.oxauth.service.external.context.DynamicScopeExternalContext) JwtSubClaimObject(org.gluu.oxauth.model.jwt.JwtSubClaimObject) GluuAttribute(org.gluu.model.GluuAttribute) Scope(org.oxauth.persistence.model.Scope) JSONObject(org.json.JSONObject) JwtSubClaimObject(org.gluu.oxauth.model.jwt.JwtSubClaimObject) JSONObject(org.json.JSONObject) Client(org.gluu.oxauth.model.registration.Client) Claim(org.gluu.oxauth.model.authorize.Claim) Scope(org.oxauth.persistence.model.Scope)

Example 49 with Client

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

the class UmaRptService method createRPTAndPersist.

public UmaRPT createRPTAndPersist(ExecutionContext executionContext, List<UmaPermission> permissions) {
    try {
        final Date creationDate = new Date();
        final Date expirationDate = rptExpirationDate();
        final Client client = executionContext.getClient();
        final String code;
        if (client.isRptAsJwt()) {
            code = createRptJwt(executionContext, permissions, creationDate, expirationDate);
        } else {
            code = UUID.randomUUID().toString() + "_" + INumGenerator.generate(8);
        }
        UmaRPT rpt = new UmaRPT(code, creationDate, expirationDate, null, client.getClientId());
        rpt.setPermissions(getPermissionDns(permissions));
        persist(rpt);
        statService.reportUmaToken(GrantType.OXAUTH_UMA_TICKET);
        return rpt;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException("Failed to generate RPT, clientId: " + executionContext.getClient().getClientId(), e);
    }
}
Also used : UmaRPT(org.gluu.oxauth.uma.authorization.UmaRPT) Client(org.gluu.oxauth.model.registration.Client) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 50 with Client

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

the class UmaResourceServiceTest method createClient.

private Client createClient(boolean deletable) throws StringEncrypter.EncryptionException {
    String clientsBaseDN = staticConfiguration.getBaseDn().getClients();
    String inum = inumService.generateClientInum();
    String generatedClientSecret = UUID.randomUUID().toString();
    final Client client = new Client();
    client.setDn("inum=" + inum + "," + clientsBaseDN);
    client.setClientName("Cleaner Timer Test");
    client.setClientId(inum);
    client.setClientSecret(clientService.encryptSecret(generatedClientSecret));
    client.setRegistrationAccessToken(HandleTokenFactory.generateHandleToken());
    client.setDeletable(deletable);
    final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    client.setClientIdIssuedAt(calendar.getTime());
    calendar.add(Calendar.MINUTE, 10);
    client.setExpirationDate(calendar.getTime());
    return client;
}
Also used : GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) 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