Search in sources :

Example 26 with Client

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

the class ClientService method getClient.

public Client getClient(String clientId) {
    if (clientId != null && !clientId.isEmpty()) {
        Client result = getClientByDn(buildClientDn(clientId));
        log.debug("Found {} entries for client id = {}", result != null ? 1 : 0, clientId);
        return result;
    }
    return null;
}
Also used : Client(org.gluu.oxauth.model.registration.Client)

Example 27 with Client

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

the class ClientService method authenticate.

/**
 * Authenticate client.
 *
 * @param clientId
 *            Client inum.
 * @param password
 *            Client password.
 * @return <code>true</code> if success, otherwise <code>false</code>.
 */
public boolean authenticate(String clientId, String password) {
    log.debug("Authenticating Client with LDAP: clientId = {}", clientId);
    boolean authenticated = false;
    try {
        Client client = getClient(clientId);
        if (client == null) {
            log.debug("Failed to find client = {}", clientId);
            return authenticated;
        }
        String decryptedClientSecret = decryptSecret(client.getClientSecret());
        authenticated = client != null && decryptedClientSecret != null && decryptedClientSecret.equals(password);
    } catch (StringEncrypter.EncryptionException e) {
        log.error(e.getMessage(), e);
    }
    return authenticated;
}
Also used : EncryptionException(org.gluu.util.security.StringEncrypter.EncryptionException) Client(org.gluu.oxauth.model.registration.Client) StringEncrypter(org.gluu.util.security.StringEncrypter)

Example 28 with Client

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

the class ClientAssertion method load.

private boolean load(AppConfiguration appConfiguration, AbstractCryptoProvider cryptoProvider, String clientId, ClientAssertionType clientAssertionType, String encodedAssertion) throws Exception {
    boolean result;
    if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
        if (StringUtils.isNotBlank(encodedAssertion)) {
            jwt = Jwt.parse(encodedAssertion);
            // TODO: Store jti this value to check for duplicates
            // Validate clientId
            String issuer = jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER);
            String subject = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER);
            List<String> audience = jwt.getClaims().getClaimAsStringList(JwtClaimName.AUDIENCE);
            Date expirationTime = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
            // SignatureAlgorithm algorithm = SignatureAlgorithm.fromName(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
            if ((clientId == null && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && issuer.equals(subject)) || (StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && clientId.equals(issuer) && issuer.equals(subject))) {
                // Validate audience
                String tokenUrl = appConfiguration.getTokenEndpoint();
                String cibaAuthUrl = appConfiguration.getBackchannelAuthenticationEndpoint();
                if (audience != null && (audience.contains(appConfiguration.getIssuer()) || audience.contains(tokenUrl) || audience.contains(cibaAuthUrl))) {
                    // Validate expiration
                    if (expirationTime.after(new Date())) {
                        ClientService clientService = CdiUtil.bean(ClientService.class);
                        Client client = clientService.getClient(subject);
                        // Validate client
                        if (client != null) {
                            JwtType jwtType = JwtType.fromString(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
                            AuthenticationMethod authenticationMethod = client.getAuthenticationMethod();
                            SignatureAlgorithm signatureAlgorithm = jwt.getHeader().getSignatureAlgorithm();
                            if (jwtType == null && signatureAlgorithm != null) {
                                jwtType = signatureAlgorithm.getJwtType();
                            }
                            if (jwtType != null && signatureAlgorithm != null && signatureAlgorithm.getFamily() != null && ((authenticationMethod == AuthenticationMethod.CLIENT_SECRET_JWT && AlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) || (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT && (AlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily()) || AlgorithmFamily.EC.equals(signatureAlgorithm.getFamily()))))) {
                                if (client.getTokenEndpointAuthSigningAlg() == null || SignatureAlgorithm.fromString(client.getTokenEndpointAuthSigningAlg()).equals(signatureAlgorithm)) {
                                    clientSecret = clientService.decryptSecret(client.getClientSecret());
                                    // Validate the crypto segment
                                    String keyId = jwt.getHeader().getKeyId();
                                    JSONObject jwks = Strings.isNullOrEmpty(client.getJwks()) ? JwtUtil.getJSONWebKeys(client.getJwksUri()) : new JSONObject(client.getJwks());
                                    String sharedSecret = clientService.decryptSecret(client.getClientSecret());
                                    boolean validSignature = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId, jwks, sharedSecret, signatureAlgorithm);
                                    if (validSignature) {
                                        result = true;
                                    } else {
                                        throw new InvalidJwtException("Invalid cryptographic segment");
                                    }
                                } else {
                                    throw new InvalidJwtException("Invalid signing algorithm");
                                }
                            } else {
                                throw new InvalidJwtException("Invalid authentication method");
                            }
                        } else {
                            throw new InvalidJwtException("Invalid client");
                        }
                    } else {
                        throw new InvalidJwtException("JWT has expired");
                    }
                } else {
                    throw new InvalidJwtException("Invalid audience: " + audience);
                }
            } else {
                throw new InvalidJwtException("Invalid clientId");
            }
        } else {
            throw new InvalidJwtException("The Client Assertion is null or empty");
        }
    } else {
        throw new InvalidJwtException("Invalid Client Assertion Type");
    }
    return result;
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) JSONObject(org.json.JSONObject) ClientService(org.gluu.oxauth.service.ClientService) JwtType(org.gluu.oxauth.model.jwt.JwtType) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) AuthenticationMethod(org.gluu.oxauth.model.common.AuthenticationMethod) Client(org.gluu.oxauth.model.registration.Client) Date(java.util.Date)

Example 29 with Client

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

the class AuthenticationService method configureSessionClient.

public Client configureSessionClient() {
    String clientInum = credentials.getUsername();
    log.debug("ConfigureSessionClient: username: '{}', credentials: '{}'", clientInum, System.identityHashCode(credentials));
    Client client = clientService.getClient(clientInum);
    configureSessionClient(client);
    return client;
}
Also used : SessionClient(org.gluu.oxauth.model.session.SessionClient) Client(org.gluu.oxauth.model.registration.Client)

Example 30 with Client

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

the class AuthorizeAction method checkPermissionGranted.

public void checkPermissionGranted() throws IOException {
    if ((clientId == null) || clientId.isEmpty()) {
        log.debug("Permission denied. client_id should be not empty.");
        permissionDenied();
        return;
    }
    Client client = null;
    try {
        client = clientService.getClient(clientId);
    } catch (EntryPersistenceException ex) {
        log.debug("Permission denied. Failed to find client by inum '{}' in LDAP.", clientId, ex);
        permissionDenied();
        return;
    }
    if (client == null) {
        log.debug("Permission denied. Failed to find client_id '{}' in LDAP.", clientId);
        permissionDenied();
        return;
    }
    // Fix the list of scopes in the authorization page. oxAuth #739
    Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
    allowedScope = org.gluu.oxauth.model.util.StringUtils.implode(grantedScopes, " ");
    SessionId session = getSession();
    List<Prompt> prompts = Prompt.fromString(prompt, " ");
    try {
        redirectUri = authorizeRestWebServiceValidator.validateRedirectUri(client, redirectUri, state, session != null ? session.getSessionAttributes().get(SESSION_USER_CODE) : null, (HttpServletRequest) externalContext.getRequest());
    } catch (WebApplicationException e) {
        log.error(e.getMessage(), e);
        permissionDenied();
        return;
    }
    try {
        session = sessionIdService.assertAuthenticatedSessionCorrespondsToNewRequest(session, acrValues);
    } catch (AcrChangedException e) {
        log.debug("There is already existing session which has another acr then {}, session: {}", acrValues, session.getId());
        if (e.isForceReAuthentication()) {
            session = handleAcrChange(session, prompts);
        } else {
            log.error("ACR is changed, please provide a supported and enabled acr value");
            permissionDenied();
            return;
        }
    }
    if (session == null || StringUtils.isBlank(session.getUserDn()) || SessionIdState.AUTHENTICATED != session.getState()) {
        Map<String, String> parameterMap = externalContext.getRequestParameterMap();
        Map<String, String> requestParameterMap = requestParameterService.getAllowedParameters(parameterMap);
        String redirectTo = "/login.xhtml";
        boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
        if (useExternalAuthenticator) {
            List<String> acrValuesList = sessionIdService.acrValuesList(this.acrValues);
            if (acrValuesList.isEmpty()) {
                acrValuesList = Arrays.asList(defaultAuthenticationMode.getName());
            }
            CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, acrValuesList);
            if (customScriptConfiguration == null) {
                log.error("Failed to get CustomScriptConfiguration. auth_step: {}, acr_values: {}", 1, this.acrValues);
                permissionDenied();
                return;
            }
            String acr = customScriptConfiguration.getName();
            requestParameterMap.put(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, acr);
            requestParameterMap.put("auth_step", Integer.toString(1));
            String tmpRedirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, 1);
            if (StringHelper.isNotEmpty(tmpRedirectTo)) {
                log.trace("Redirect to person authentication login page: {}", tmpRedirectTo);
                redirectTo = tmpRedirectTo;
            }
        }
        // Store Remote IP
        requestParameterMap.put(Constants.REMOTE_IP, getRemoteIp());
        // User Code used in Device Authz flow
        if (session != null && session.getSessionAttributes().containsKey(SESSION_USER_CODE)) {
            String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
            requestParameterMap.put(SESSION_USER_CODE, userCode);
        }
        // Create unauthenticated session
        SessionId unauthenticatedSession = sessionIdService.generateUnauthenticatedSessionId(null, new Date(), SessionIdState.UNAUTHENTICATED, requestParameterMap, false);
        unauthenticatedSession.setSessionAttributes(requestParameterMap);
        unauthenticatedSession.addPermission(clientId, false);
        // Copy ACR script parameters
        if (appConfiguration.getKeepAuthenticatorAttributesOnAcrChange()) {
            authenticationService.copyAuthenticatorExternalAttributes(session, unauthenticatedSession);
        }
        // #1030, fix for flow 4 - transfer previous session permissions to new session
        if (session != null && session.getPermissionGrantedMap() != null && session.getPermissionGrantedMap().getPermissionGranted() != null) {
            for (Map.Entry<String, Boolean> entity : session.getPermissionGrantedMap().getPermissionGranted().entrySet()) {
                unauthenticatedSession.addPermission(entity.getKey(), entity.getValue());
            }
            // #1030, remove previous session
            sessionIdService.remove(session);
        }
        // always persist is prompt is not none
        boolean persisted = sessionIdService.persistSessionId(unauthenticatedSession, !prompts.contains(Prompt.NONE));
        if (persisted && log.isTraceEnabled()) {
            log.trace("Session '{}' persisted to LDAP", unauthenticatedSession.getId());
        }
        this.sessionId = unauthenticatedSession.getId();
        cookieService.createSessionIdCookie(unauthenticatedSession, false);
        cookieService.creatRpOriginIdCookie(redirectUri);
        identity.setSessionId(unauthenticatedSession);
        Map<String, Object> loginParameters = new HashMap<String, Object>();
        if (requestParameterMap.containsKey(AuthorizeRequestParam.LOGIN_HINT)) {
            loginParameters.put(AuthorizeRequestParam.LOGIN_HINT, requestParameterMap.get(AuthorizeRequestParam.LOGIN_HINT));
        }
        boolean enableRedirect = StringHelper.toBoolean(System.getProperty("gluu.enable-redirect", "false"), false);
        if (!enableRedirect && redirectTo.toLowerCase().endsWith("xhtml")) {
            if (redirectTo.toLowerCase().endsWith("postlogin.xhtml")) {
                authenticator.authenticateWithOutcome();
            } else {
                authenticator.prepareAuthenticationForStep(unauthenticatedSession);
                facesService.renderView(redirectTo);
            }
        } else {
            facesService.redirectWithExternal(redirectTo, loginParameters);
        }
        return;
    }
    String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
    if (StringUtils.isBlank(userCode) && StringUtils.isBlank(redirectionUriService.validateRedirectionUri(clientId, redirectUri))) {
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.setResponseStatus(HttpServletResponse.SC_BAD_REQUEST);
        externalContext.setResponseContentType(MediaType.APPLICATION_JSON);
        externalContext.getResponseOutputWriter().write(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state, ""));
        facesContext.responseComplete();
    }
    if (log.isTraceEnabled()) {
        log.trace("checkPermissionGranted, userDn = " + session.getUserDn());
    }
    if (prompts.contains(Prompt.SELECT_ACCOUNT)) {
        Map requestParameterMap = requestParameterService.getAllowedParameters(externalContext.getRequestParameterMap());
        facesService.redirect("/selectAccount.xhtml", requestParameterMap);
        return;
    }
    if (prompts.contains(Prompt.NONE) && prompts.size() > 1) {
        invalidRequest();
        return;
    }
    ExternalPostAuthnContext postAuthnContext = new ExternalPostAuthnContext(client, session, (HttpServletRequest) externalContext.getRequest(), (HttpServletResponse) externalContext.getResponse());
    final boolean forceAuthorization = externalPostAuthnService.externalForceAuthorization(client, postAuthnContext);
    final boolean hasConsentPrompt = prompts.contains(Prompt.CONSENT);
    if (!hasConsentPrompt && !forceAuthorization) {
        if (appConfiguration.getTrustedClientEnabled() && client.getTrustedClient()) {
            // if trusted client = true, then skip authorization page and grant access directly
            permissionGranted(session);
            return;
        } else if (ServerUtil.isTrue(appConfiguration.getSkipAuthorizationForOpenIdScopeAndPairwiseId()) && SubjectType.PAIRWISE.toString().equals(client.getSubjectType()) && hasOnlyOpenidScope()) {
            // If a client has only openid scope and pairwise id, person should not have to authorize. oxAuth-743
            permissionGranted(session);
            return;
        }
        final User user = sessionIdService.getUser(session);
        ClientAuthorization clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
        if (clientAuthorization != null && clientAuthorization.getScopes() != null && Arrays.asList(clientAuthorization.getScopes()).containsAll(org.gluu.oxauth.model.util.StringUtils.spaceSeparatedToList(scope))) {
            permissionGranted(session);
            return;
        }
    }
    if (externalConsentGatheringService.isEnabled()) {
        if (consentGatherer.isConsentGathered()) {
            log.trace("Consent-gathered flow passed successfully");
            permissionGranted(session);
            return;
        }
        log.trace("Starting external consent-gathering flow");
        boolean result = consentGatherer.configure(session.getUserDn(), clientId, state);
        if (!result) {
            log.error("Failed to initialize external consent-gathering flow.");
            permissionDenied();
            return;
        }
    }
}
Also used : User(org.gluu.oxauth.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) HttpServletRequest(javax.servlet.http.HttpServletRequest) AcrChangedException(org.gluu.oxauth.model.exception.AcrChangedException) ExternalContext(javax.faces.context.ExternalContext) Client(org.gluu.oxauth.model.registration.Client) SessionId(org.gluu.oxauth.model.common.SessionId) ClientAuthorization(org.gluu.oxauth.model.ldap.ClientAuthorization) ExternalPostAuthnContext(org.gluu.oxauth.service.external.context.ExternalPostAuthnContext) Date(java.util.Date) Prompt(org.gluu.oxauth.model.common.Prompt) CustomScriptConfiguration(org.gluu.model.custom.script.conf.CustomScriptConfiguration) Map(java.util.Map) HashMap(java.util.HashMap)

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