Search in sources :

Example 46 with User

use of io.jans.as.common.model.common.User in project jans by JanssenProject.

the class ScopeServiceTest method buildRegularUser.

private User buildRegularUser(String userId, Date createdAt, Date updatedAt) {
    final User user = new User();
    user.setUpdatedAt(updatedAt);
    user.setCreatedAt(createdAt);
    user.setUserId(userId);
    user.setAttribute("emailVerified", "true", false);
    user.setAttribute("lastLogon", "20211012135114.554Z", false);
    user.setAttribute("metadata", "{}", false);
    user.setDn("DN");
    return user;
}
Also used : User(io.jans.as.common.model.common.User)

Example 47 with User

use of io.jans.as.common.model.common.User in project jans by JanssenProject.

the class ScopeServiceTest method getClaims_GluuAttributeLdapNameBlank_EmptyResult.

@Test
public void getClaims_GluuAttributeLdapNameBlank_EmptyResult() throws Exception {
    User user = new User();
    Scope scope = new Scope();
    scope.setClaims(Lists.newArrayList("claim1", "claim2"));
    GluuAttribute gluuAttribute = new GluuAttribute();
    gluuAttribute.setClaimName("CLAIM_NAME");
    when(attributeService.getAttributeByDn(anyString())).thenReturn(gluuAttribute);
    Map<String, Object> result = scopeService.getClaims(user, scope);
    assertNotNull(result);
    assertEquals(result.size(), 0);
    verify(log, times(2)).error(startsWith("Failed to get claim because name is not set for attribute"), (Object) isNull());
    verifyNoMoreInteractions(log);
    verifyNoMoreInteractions(attributeService);
}
Also used : User(io.jans.as.common.model.common.User) Scope(io.jans.as.persistence.model.Scope) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) GluuAttribute(io.jans.model.GluuAttribute) Test(org.testng.annotations.Test)

Example 48 with User

use of io.jans.as.common.model.common.User in project jans by JanssenProject.

the class AuthorizationGrant method createAccessTokenAsJwt.

private String createAccessTokenAsJwt(AccessToken accessToken, ExecutionContext context) throws Exception {
    final User user = getUser();
    final Client client = getClient();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
    if (client.getAccessTokenSigningAlg() != null && SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg()) != null) {
        signatureAlgorithm = SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg());
    }
    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
    final Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setClaim("scope", Lists.newArrayList(getScopes()));
    jwt.getClaims().setClaim("client_id", getClientId());
    jwt.getClaims().setClaim("username", user != null ? user.getAttribute("displayName") : null);
    jwt.getClaims().setClaim("token_type", accessToken.getTokenType().getName());
    // guarantee uniqueness : without it we can get race condition
    jwt.getClaims().setClaim("code", accessToken.getCode());
    jwt.getClaims().setExpirationTime(accessToken.getExpirationDate());
    jwt.getClaims().setIssuedAt(accessToken.getCreationDate());
    jwt.getClaims().setSubjectIdentifier(getSub());
    jwt.getClaims().setClaim("x5t#S256", accessToken.getX5ts256());
    // DPoP
    final String dpop = context.getDpop();
    if (StringUtils.isNotBlank(dpop)) {
        jwt.getClaims().setNotBefore(accessToken.getCreationDate());
        JSONObject cnf = new JSONObject();
        cnf.put("jkt", dpop);
        jwt.getClaims().setClaim("cnf", cnf);
    }
    Audience.setAudience(jwt.getClaims(), getClient());
    if (isTrue(client.getAttributes().getRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims())) {
        runIntrospectionScriptAndInjectValuesIntoJwt(jwt, context);
    }
    final String accessTokenCode = jwtSigner.sign().toString();
    if (log.isTraceEnabled())
        log.trace("Created access token JWT: {}", accessTokenCode + ", claims: " + jwt.getClaims().toJsonString());
    return accessTokenCode;
}
Also used : JwtSigner(io.jans.as.server.model.token.JwtSigner) User(io.jans.as.common.model.common.User) JSONObject(org.json.JSONObject) Jwt(io.jans.as.model.jwt.Jwt) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Client(io.jans.as.common.model.registration.Client)

Example 49 with User

use of io.jans.as.common.model.common.User in project jans by JanssenProject.

the class AuthorizationGrantList method asGrant.

public AuthorizationGrant asGrant(TokenEntity tokenEntity) {
    if (tokenEntity != null) {
        final AuthorizationGrantType grantType = AuthorizationGrantType.fromString(tokenEntity.getGrantType());
        if (grantType != null) {
            final User user = userService.getUser(tokenEntity.getUserId());
            final Client client = clientService.getClient(tokenEntity.getClientId());
            final Date authenticationTime = tokenEntity.getAuthenticationTime();
            final String nonce = tokenEntity.getNonce();
            AuthorizationGrant result;
            switch(grantType) {
                case AUTHORIZATION_CODE:
                    AuthorizationCodeGrant authorizationCodeGrant = grantInstance.select(AuthorizationCodeGrant.class).get();
                    authorizationCodeGrant.init(user, client, authenticationTime);
                    result = authorizationCodeGrant;
                    break;
                case CLIENT_CREDENTIALS:
                    ClientCredentialsGrant clientCredentialsGrant = grantInstance.select(ClientCredentialsGrant.class).get();
                    clientCredentialsGrant.init(user, client);
                    result = clientCredentialsGrant;
                    break;
                case IMPLICIT:
                    ImplicitGrant implicitGrant = grantInstance.select(ImplicitGrant.class).get();
                    implicitGrant.init(user, client, authenticationTime);
                    result = implicitGrant;
                    break;
                case RESOURCE_OWNER_PASSWORD_CREDENTIALS:
                    ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = grantInstance.select(ResourceOwnerPasswordCredentialsGrant.class).get();
                    resourceOwnerPasswordCredentialsGrant.init(user, client);
                    result = resourceOwnerPasswordCredentialsGrant;
                    break;
                case CIBA:
                    CIBAGrant cibaGrant = grantInstance.select(CIBAGrant.class).get();
                    cibaGrant.init(user, AuthorizationGrantType.CIBA, client, tokenEntity.getCreationDate());
                    result = cibaGrant;
                    break;
                case DEVICE_CODE:
                    DeviceCodeGrant deviceCodeGrant = grantInstance.select(DeviceCodeGrant.class).get();
                    deviceCodeGrant.init(user, AuthorizationGrantType.DEVICE_CODE, client, tokenEntity.getCreationDate());
                    result = deviceCodeGrant;
                    break;
                default:
                    return null;
            }
            final String grantId = tokenEntity.getGrantId();
            final String jwtRequest = tokenEntity.getJwtRequest();
            final String authMode = tokenEntity.getAuthMode();
            final String sessionDn = tokenEntity.getSessionDn();
            final String claims = tokenEntity.getClaims();
            result.setTokenBindingHash(tokenEntity.getTokenBindingHash());
            result.setNonce(nonce);
            result.setX5cs256(tokenEntity.getAttributes().getX5cs256());
            result.setTokenEntity(tokenEntity);
            if (StringUtils.isNotBlank(grantId)) {
                result.setGrantId(grantId);
            }
            result.setScopes(Util.splittedStringAsList(tokenEntity.getScope(), " "));
            result.setCodeChallenge(tokenEntity.getCodeChallenge());
            result.setCodeChallengeMethod(tokenEntity.getCodeChallengeMethod());
            if (StringUtils.isNotBlank(jwtRequest)) {
                try {
                    result.setJwtAuthorizationRequest(new JwtAuthorizationRequest(appConfiguration, cryptoProvider, jwtRequest, client));
                } catch (Exception e) {
                    log.trace(e.getMessage(), e);
                }
            }
            result.setAcrValues(authMode);
            result.setSessionDn(sessionDn);
            result.setClaims(claims);
            if (tokenEntity.getTokenTypeEnum() != null) {
                switch(tokenEntity.getTokenTypeEnum()) {
                    case AUTHORIZATION_CODE:
                        if (result instanceof AuthorizationCodeGrant) {
                            final AuthorizationCode code = new AuthorizationCode(tokenEntity.getTokenCode(), tokenEntity.getCreationDate(), tokenEntity.getExpirationDate());
                            final AuthorizationCodeGrant g = (AuthorizationCodeGrant) result;
                            g.setAuthorizationCode(code);
                        }
                        break;
                    case REFRESH_TOKEN:
                        final RefreshToken refreshToken = new RefreshToken(tokenEntity.getTokenCode(), tokenEntity.getCreationDate(), tokenEntity.getExpirationDate());
                        result.setRefreshTokens(Collections.singletonList(refreshToken));
                        break;
                    case ACCESS_TOKEN:
                        final AccessToken accessToken = new AccessToken(tokenEntity.getTokenCode(), tokenEntity.getCreationDate(), tokenEntity.getExpirationDate());
                        accessToken.setDpop(tokenEntity.getDpop());
                        result.setAccessTokens(Collections.singletonList(accessToken));
                        break;
                    case ID_TOKEN:
                        final IdToken idToken = new IdToken(tokenEntity.getTokenCode(), tokenEntity.getCreationDate(), tokenEntity.getExpirationDate());
                        result.setIdToken(idToken);
                        break;
                    case LONG_LIVED_ACCESS_TOKEN:
                        final AccessToken longLivedAccessToken = new AccessToken(tokenEntity.getTokenCode(), tokenEntity.getCreationDate(), tokenEntity.getExpirationDate());
                        result.setLongLivedAccessToken(longLivedAccessToken);
                        break;
                }
            }
            return result;
        }
    }
    return null;
}
Also used : User(io.jans.as.common.model.common.User) Date(java.util.Date) JwtAuthorizationRequest(io.jans.as.server.model.authorize.JwtAuthorizationRequest) Client(io.jans.as.common.model.registration.Client)

Example 50 with User

use of io.jans.as.common.model.common.User in project jans by JanssenProject.

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. Jans Auth #739
    Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
    allowedScope = io.jans.as.model.util.StringUtils.implode(grantedScopes, " ");
    SessionId session = getSession();
    List<io.jans.as.model.common.Prompt> prompts = io.jans.as.model.common.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
        String remoteIp = networkService.getRemoteIp();
        requestParameterMap.put(Constants.REMOTE_IP, remoteIp);
        // 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(io.jans.as.model.common.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(io.jans.as.model.authorize.AuthorizeRequestParam.LOGIN_HINT)) {
            loginParameters.put(io.jans.as.model.authorize.AuthorizeRequestParam.LOGIN_HINT, requestParameterMap.get(io.jans.as.model.authorize.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(io.jans.as.model.authorize.AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state, ""));
        facesContext.responseComplete();
    }
    if (log.isTraceEnabled()) {
        log.trace("checkPermissionGranted, userDn = " + session.getUserDn());
    }
    if (prompts.contains(io.jans.as.model.common.Prompt.SELECT_ACCOUNT)) {
        Map requestParameterMap = requestParameterService.getAllowedParameters(externalContext.getRequestParameterMap());
        facesService.redirect("/selectAccount.xhtml", requestParameterMap);
        return;
    }
    if (prompts.contains(io.jans.as.model.common.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(io.jans.as.model.common.Prompt.CONSENT);
    if (!hasConsentPrompt && !forceAuthorization) {
        final boolean isTrusted = isTrue(appConfiguration.getTrustedClientEnabled()) && client.getTrustedClient();
        final boolean canGrantAccess = isTrue(appConfiguration.getSkipAuthorizationForOpenIdScopeAndPairwiseId()) && SubjectType.PAIRWISE.equals(client.getSubjectType()) && hasOnlyOpenidScope();
        // There is no need to present the consent page:
        // If Client is a Trusted Client.
        // If a client is configured for pairwise identifiers, and the openid scope is the only scope requested.
        // Also, we should make sure that the claims request is not enabled.
        final boolean isPairwiseWithOnlyOpenIdScope = client.getSubjectType() == SubjectType.PAIRWISE && grantedScopes.size() == 1 && grantedScopes.contains(DefaultScope.OPEN_ID.toString()) && scope.equals(DefaultScope.OPEN_ID.toString()) && claims == null && request == null;
        if (isTrusted || canGrantAccess || isPairwiseWithOnlyOpenIdScope) {
            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(io.jans.as.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(io.jans.as.common.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) HttpServletRequest(javax.servlet.http.HttpServletRequest) AcrChangedException(io.jans.as.server.model.exception.AcrChangedException) ExternalContext(javax.faces.context.ExternalContext) Client(io.jans.as.common.model.registration.Client) SessionId(io.jans.as.server.model.common.SessionId) ClientAuthorization(io.jans.as.server.model.ldap.ClientAuthorization) ExternalPostAuthnContext(io.jans.as.server.service.external.context.ExternalPostAuthnContext) Prompt(io.jans.as.model.common.Prompt) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Aggregations

User (io.jans.as.common.model.common.User)95 Test (org.testng.annotations.Test)54 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)35 CustomObjectAttribute (io.jans.orm.model.base.CustomObjectAttribute)12 Client (io.jans.as.common.model.registration.Client)11 Date (java.util.Date)11 SessionId (io.jans.as.server.model.common.SessionId)9 Scope (io.jans.as.persistence.model.Scope)8 ArrayList (java.util.ArrayList)8 SimpleUser (io.jans.as.common.model.common.SimpleUser)7 WebApplicationException (javax.ws.rs.WebApplicationException)6 OAuth2AuditLog (io.jans.as.server.model.audit.OAuth2AuditLog)5 Response (javax.ws.rs.core.Response)5 JsonWebResponse (io.jans.as.model.token.JsonWebResponse)4 AuthorizationGrant (io.jans.as.server.model.common.AuthorizationGrant)4 EntryPersistenceException (io.jans.orm.exception.EntryPersistenceException)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)3 CibaRequestCacheControl (io.jans.as.server.model.common.CibaRequestCacheControl)3 CustomAttribute (io.jans.orm.model.base.CustomAttribute)3