Search in sources :

Example 36 with User

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

the class RevokeSessionRestWebService method requestRevokeSession.

@POST
@Path("/revoke_session")
@Produces({ MediaType.APPLICATION_JSON })
public Response requestRevokeSession(@FormParam("user_criterion_key") String userCriterionKey, @FormParam("user_criterion_value") String userCriterionValue, @Context HttpServletRequest request, @Context HttpServletResponse response, @Context SecurityContext sec) {
    try {
        log.debug("Attempting to revoke session: userCriterionKey = {}, userCriterionValue = {}, isSecure = {}", userCriterionKey, userCriterionValue, sec.isSecure());
        errorResponseFactory.validateComponentEnabled(ComponentType.REVOKE_SESSION);
        validateAccess();
        final User user = userService.getUserByAttribute(userCriterionKey, userCriterionValue);
        if (user == null) {
            log.trace("Unable to find user by {}={}", userCriterionKey, userCriterionValue);
            // no error because we don't want to disclose internal AS info about users
            return Response.ok().build();
        }
        List<SessionId> sessionIdList = sessionIdService.findByUser(user.getDn());
        if (sessionIdList == null || sessionIdList.isEmpty()) {
            log.trace("No sessions found for user uid: {}, dn: {}", user.getUserId(), user.getDn());
            return Response.ok().build();
        }
        final List<SessionId> authenticatedSessions = sessionIdList.stream().filter(sessionId -> sessionId.getState() == SessionIdState.AUTHENTICATED).collect(Collectors.toList());
        sessionIdService.remove(authenticatedSessions);
        log.debug("Revoked {} user's sessions (user: {})", authenticatedSessions.size(), user.getUserId());
        return Response.ok().build();
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.status(500).build();
    }
}
Also used : Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) Identity(io.jans.as.server.security.Identity) SessionId(io.jans.as.server.model.common.SessionId) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) User(io.jans.as.common.model.common.User) ScopeService(io.jans.as.server.service.ScopeService) SessionIdState(io.jans.as.server.model.common.SessionIdState) UserService(io.jans.as.server.service.UserService) Constants(io.jans.as.server.model.config.Constants) FormParam(javax.ws.rs.FormParam) EndSessionErrorResponseType(io.jans.as.model.session.EndSessionErrorResponseType) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) ErrorResponseFactory(io.jans.as.model.error.ErrorResponseFactory) HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionIdService(io.jans.as.server.service.SessionIdService) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) ComponentType(io.jans.as.model.common.ComponentType) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(io.jans.as.server.model.session.SessionClient) ArrayUtils(org.apache.commons.lang.ArrayUtils) User(io.jans.as.common.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) SessionId(io.jans.as.server.model.common.SessionId) WebApplicationException(javax.ws.rs.WebApplicationException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 37 with User

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

the class SectorIdentifierService method getSub.

public String getSub(IAuthorizationGrant grant) {
    Client client = grant.getClient();
    User user = grant.getUser();
    if (user == null) {
        log.trace("User is null, return blank sub");
        return "";
    }
    if (client == null) {
        log.trace("Client is null, return blank sub.");
        return "";
    }
    return getSub(client, user, grant instanceof CIBAGrant);
}
Also used : User(io.jans.as.common.model.common.User) CIBAGrant(io.jans.as.server.model.common.CIBAGrant) Client(io.jans.as.common.model.registration.Client)

Example 38 with User

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

the class SessionIdService method setSessionIdStateAuthenticated.

public SessionId setSessionIdStateAuthenticated(HttpServletRequest httpRequest, HttpServletResponse httpResponse, SessionId sessionId, String userDn) {
    sessionId.setUserDn(userDn);
    sessionId.setAuthenticationTime(new Date());
    sessionId.setState(SessionIdState.AUTHENTICATED);
    final User user = getUser(sessionId);
    if (user != null) {
        statService.reportActiveUser(user.getUserId());
    }
    final boolean persisted;
    if (isTrue(appConfiguration.getChangeSessionIdOnAuthentication()) && httpResponse != null) {
        final String oldSessionId = sessionId.getId();
        final String newSessionId = UUID.randomUUID().toString();
        log.debug("Changing session id from {} to {} ...", oldSessionId, newSessionId);
        remove(sessionId);
        sessionId.setId(newSessionId);
        sessionId.setDn(buildDn(newSessionId));
        sessionId.getSessionAttributes().put(SessionId.OLD_SESSION_ID_ATTR_KEY, oldSessionId);
        if (isTrue(sessionId.getIsJwt())) {
            sessionId.setJwt(generateJwt(sessionId, sessionId.getUserDn()).asString());
        }
        persisted = persistSessionId(sessionId, true);
        cookieService.createSessionIdCookie(sessionId, httpRequest, httpResponse, false);
        log.debug("Session identifier changed from {} to {} .", oldSessionId, newSessionId);
    } else {
        persisted = updateSessionId(sessionId, true, true, true);
    }
    auditLogging(sessionId);
    log.trace("Authenticated session, id = '{}', state = '{}', persisted = '{}'", sessionId.getId(), sessionId.getState(), persisted);
    if (externalApplicationSessionService.isEnabled()) {
        String userName = sessionId.getSessionAttributes().get(Constants.AUTHENTICATED_USER);
        boolean externalResult = externalApplicationSessionService.executeExternalStartSessionMethods(httpRequest, sessionId);
        log.info("Start session result for '{}': '{}'", userName, externalResult);
        if (!externalResult) {
            reinitLogin(sessionId, true);
            throw new InvalidSessionStateException("Session creation is prohibited by external session script!");
        }
        externalEvent(new SessionEvent(SessionEventType.AUTHENTICATED, sessionId).setHttpRequest(httpRequest).setHttpResponse(httpResponse));
    }
    return sessionId;
}
Also used : SessionEvent(io.jans.as.server.service.external.session.SessionEvent) User(io.jans.as.common.model.common.User) InvalidSessionStateException(io.jans.as.server.model.exception.InvalidSessionStateException) Date(java.util.Date)

Example 39 with User

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

the class AuthenticationPersistenceService method save.

public void save(Fido2AuthenticationData authenticationData) {
    String userName = authenticationData.getUsername();
    User user = userService.getUser(userName, "inum");
    if (user == null) {
        if (appConfiguration.getFido2Configuration().isUserAutoEnrollment()) {
            user = userService.addDefaultUser(userName);
        } else {
            throw new Fido2RuntimeException("Auto user enrollment was disabled. User not exists!");
        }
    }
    String userInum = userService.getUserInum(user);
    prepareBranch(userInum);
    Date now = new GregorianCalendar(TimeZone.getTimeZone("UTC")).getTime();
    final String id = UUID.randomUUID().toString();
    String dn = getDnForAuthenticationEntry(userInum, id);
    Fido2AuthenticationEntry authenticationEntity = new Fido2AuthenticationEntry(dn, authenticationData.getId(), now, userInum, authenticationData);
    authenticationEntity.setAuthenticationStatus(authenticationData.getStatus());
    authenticationData.setCreatedDate(now);
    authenticationData.setCreatedBy(userName);
    persistenceEntryManager.persist(authenticationEntity);
}
Also used : User(io.jans.as.common.model.common.User) GregorianCalendar(java.util.GregorianCalendar) Fido2AuthenticationEntry(io.jans.fido2.model.entry.Fido2AuthenticationEntry) Fido2RuntimeException(io.jans.fido2.exception.Fido2RuntimeException) Date(java.util.Date)

Example 40 with User

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

the class IdTokenFactory method fillClaims.

private void fillClaims(JsonWebResponse jwr, IAuthorizationGrant authorizationGrant, AuthorizationCode authorizationCode, AccessToken accessToken, RefreshToken refreshToken, ExecutionContext executionContext) throws Exception {
    jwr.getClaims().setIssuer(appConfiguration.getIssuer());
    Audience.setAudience(jwr.getClaims(), authorizationGrant.getClient());
    int lifeTime = appConfiguration.getIdTokenLifetime();
    int lifetimeFromScript = externalUpdateTokenService.getIdTokenLifetimeInSeconds(ExternalUpdateTokenContext.of(executionContext));
    if (lifetimeFromScript > 0) {
        lifeTime = lifetimeFromScript;
        log.trace("Override id token lifetime with value from script: {}", lifetimeFromScript);
    }
    Calendar calendar = Calendar.getInstance();
    Date issuedAt = calendar.getTime();
    calendar.add(Calendar.SECOND, lifeTime);
    Date expiration = calendar.getTime();
    jwr.getClaims().setExpirationTime(expiration);
    jwr.getClaims().setIssuedAt(issuedAt);
    jwr.setClaim("code", UUID.randomUUID().toString());
    if (executionContext.getPreProcessing() != null) {
        executionContext.getPreProcessing().apply(jwr);
    }
    final SessionId session = sessionIdService.getSessionByDn(authorizationGrant.getSessionDn());
    if (session != null) {
        jwr.setClaim("sid", session.getOutsideSid());
    }
    if (authorizationGrant.getAcrValues() != null) {
        jwr.setClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, authorizationGrant.getAcrValues());
        setAmrClaim(jwr, authorizationGrant.getAcrValues());
    }
    String nonce = executionContext.getNonce();
    if (StringUtils.isNotBlank(nonce)) {
        jwr.setClaim(JwtClaimName.NONCE, nonce);
    }
    if (authorizationGrant.getAuthenticationTime() != null) {
        jwr.getClaims().setClaim(JwtClaimName.AUTHENTICATION_TIME, authorizationGrant.getAuthenticationTime());
    }
    if (authorizationCode != null) {
        String codeHash = AbstractToken.getHash(authorizationCode.getCode(), jwr.getHeader().getSignatureAlgorithm());
        jwr.setClaim(JwtClaimName.CODE_HASH, codeHash);
    }
    if (accessToken != null) {
        String accessTokenHash = AbstractToken.getHash(accessToken.getCode(), jwr.getHeader().getSignatureAlgorithm());
        jwr.setClaim(JwtClaimName.ACCESS_TOKEN_HASH, accessTokenHash);
    }
    String state = executionContext.getState();
    if (Strings.isNotBlank(state)) {
        String stateHash = AbstractToken.getHash(state, jwr.getHeader().getSignatureAlgorithm());
        jwr.setClaim(JwtClaimName.STATE_HASH, stateHash);
    }
    if (authorizationGrant.getGrantType() != null) {
        jwr.setClaim("grant", authorizationGrant.getGrantType().getValue());
    }
    jwr.setClaim(JwtClaimName.OX_OPENID_CONNECT_VERSION, appConfiguration.getOxOpenIdConnectVersion());
    User user = authorizationGrant.getUser();
    List<Scope> dynamicScopes = new ArrayList<>();
    if (executionContext.isIncludeIdTokenClaims() && authorizationGrant.getClient().isIncludeClaimsInIdToken()) {
        for (String scopeName : executionContext.getScopes()) {
            Scope scope = scopeService.getScopeById(scopeName);
            if (scope == null) {
                continue;
            }
            if (DYNAMIC == scope.getScopeType()) {
                dynamicScopes.add(scope);
                continue;
            }
            Map<String, Object> claims = scopeService.getClaims(user, scope);
            if (Boolean.TRUE.equals(scope.isGroupClaims())) {
                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) value);
                    } else {
                        groupClaim.setClaim(key, (String) value);
                    }
                }
                jwr.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) {
                        jwr.getClaims().setClaim(key, (List) value);
                    } else if (value instanceof Boolean) {
                        jwr.getClaims().setClaim(key, (Boolean) value);
                    } else if (value instanceof Date) {
                        jwr.getClaims().setClaim(key, ((Date) value).getTime() / 1000);
                    } else {
                        jwr.setClaim(key, (String) value);
                    }
                }
            }
            jwr.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute("inum"));
        }
    }
    setClaimsFromJwtAuthorizationRequest(jwr, authorizationGrant, executionContext.getScopes());
    setClaimsFromRequestedClaims(executionContext.getClaimsAsString(), jwr, user);
    filterClaimsBasedOnAccessToken(jwr, accessToken, authorizationCode);
    jwrService.setSubjectIdentifier(jwr, authorizationGrant);
    if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) {
        final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant);
        DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jwr, unmodifiableAuthorizationGrant);
        externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext);
    }
    processCiba(jwr, authorizationGrant, refreshToken);
    if (executionContext.getPostProcessor() != null) {
        executionContext.getPostProcessor().apply(jwr);
    }
}
Also used : User(io.jans.as.common.model.common.User) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) DynamicScopeExternalContext(io.jans.as.server.service.external.context.DynamicScopeExternalContext) Date(java.util.Date) JwtSubClaimObject(io.jans.as.model.jwt.JwtSubClaimObject) UnmodifiableAuthorizationGrant(io.jans.as.server.model.common.UnmodifiableAuthorizationGrant) Scope(io.jans.as.persistence.model.Scope) JSONObject(org.json.JSONObject) JwtSubClaimObject(io.jans.as.model.jwt.JwtSubClaimObject) List(java.util.List) ArrayList(java.util.ArrayList) SessionId(io.jans.as.server.model.common.SessionId) Map(java.util.Map)

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