Search in sources :

Example 1 with Client

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

the class AuthorizeAction method getRequestedClaims.

public List<String> getRequestedClaims() {
    Set<String> result = new HashSet<String>();
    String requestJwt = request;
    if (StringUtils.isBlank(requestJwt) && StringUtils.isNotBlank(requestUri)) {
        try {
            URI reqUri = new URI(requestUri);
            String reqUriHash = reqUri.getFragment();
            String reqUriWithoutFragment = reqUri.getScheme() + ":" + reqUri.getSchemeSpecificPart();
            javax.ws.rs.client.Client clientRequest = ClientBuilder.newClient();
            try {
                Response clientResponse = clientRequest.target(reqUriWithoutFragment).request().buildGet().invoke();
                clientRequest.close();
                int status = clientResponse.getStatus();
                if (status == 200) {
                    String entity = clientResponse.readEntity(String.class);
                    if (StringUtils.isBlank(reqUriHash)) {
                        requestJwt = entity;
                    } else {
                        String hash = Base64Util.base64urlencode(JwtUtil.getMessageDigestSHA256(entity));
                        if (StringUtils.equals(reqUriHash, hash)) {
                            requestJwt = entity;
                        }
                    }
                }
            } finally {
                clientRequest.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    if (StringUtils.isNotBlank(requestJwt)) {
        try {
            Client client = clientService.getClient(clientId);
            if (client != null) {
                JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(appConfiguration, cryptoProvider, request, client);
                if (jwtAuthorizationRequest.getUserInfoMember() != null) {
                    for (Claim claim : jwtAuthorizationRequest.getUserInfoMember().getClaims()) {
                        result.add(claim.getName());
                    }
                }
                if (jwtAuthorizationRequest.getIdTokenMember() != null) {
                    for (Claim claim : jwtAuthorizationRequest.getIdTokenMember().getClaims()) {
                        result.add(claim.getName());
                    }
                }
            }
        } catch (EntryPersistenceException | InvalidJwtException e) {
            log.error(e.getMessage(), e);
        }
    }
    return new ArrayList<>(result);
}
Also used : InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) URI(java.net.URI) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) AcrChangedException(io.jans.as.server.model.exception.AcrChangedException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) IOException(java.io.IOException) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) JwtAuthorizationRequest(io.jans.as.server.model.authorize.JwtAuthorizationRequest) Client(io.jans.as.common.model.registration.Client) Claim(io.jans.as.server.model.authorize.Claim)

Example 2 with Client

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

the class DeviceAuthorizationRestWebServiceImpl method deviceAuthorization.

@Override
public Response deviceAuthorization(String clientId, String scope, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    // it may be encoded
    scope = ServerUtil.urlDecode(scope);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.DEVICE_CODE_AUTHORIZATION);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setScope(scope);
    try {
        log.debug("Attempting to request device codes: clientId = {}, scope = {}", clientId, scope);
        errorResponseFactory.validateComponentEnabled(ComponentType.DEVICE_AUTHZ);
        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 device authorization, clientId: {}", clientId);
                throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, INVALID_CLIENT, "");
            }
        }
        if (client == null) {
            log.trace("Client is not unknown. Skip revoking.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, INVALID_CLIENT, "");
        }
        if (!deviceAuthorizationService.hasDeviceCodeCompatibility(client)) {
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, INVALID_GRANT, "");
        }
        List<String> scopes = new ArrayList<>();
        if (StringHelper.isNotEmpty(scope)) {
            Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
            scopes.addAll(grantedScopes);
        }
        // Entropy 20^8 which is suggested in the RFC8628 section 6.1
        String userCode = StringUtils.generateRandomReadableCode((byte) 8);
        // Entropy 160 bits which is over userCode entropy based on RFC8628 section 5.2
        String deviceCode = StringUtils.generateRandomCode((byte) 24);
        URI verificationUri = UriBuilder.fromUri(appConfiguration.getIssuer()).path("device-code").build();
        int expiresIn = appConfiguration.getDeviceAuthzRequestExpiresIn();
        int interval = appConfiguration.getDeviceAuthzTokenPollInterval();
        long lastAccess = System.currentTimeMillis();
        DeviceAuthorizationStatus status = DeviceAuthorizationStatus.PENDING;
        DeviceAuthorizationCacheControl deviceAuthorizationCacheControl = new DeviceAuthorizationCacheControl(userCode, deviceCode, client, scopes, verificationUri, expiresIn, interval, lastAccess, status);
        deviceAuthorizationService.saveInCache(deviceAuthorizationCacheControl, true, true);
        log.info("Device authorization flow initiated, userCode: {}, deviceCode: {}, clientId: {}, verificationUri: {}, expiresIn: {}, interval: {}", userCode, deviceCode, clientId, verificationUri, expiresIn, interval);
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
        return Response.ok().entity(getResponseJSONObject(deviceAuthorizationCacheControl).toString(4).replace("\\/", "/")).type(MediaType.APPLICATION_JSON_TYPE).build();
    } catch (WebApplicationException wae) {
        throw wae;
    } catch (Exception e) {
        log.error("Problems processing device authorization init flow, clientId: {}, scope: {}", clientId, scope, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
}
Also used : DeviceAuthorizationCacheControl(io.jans.as.server.model.common.DeviceAuthorizationCacheControl) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(io.jans.as.server.model.session.SessionClient) OAuth2AuditLog(io.jans.as.server.model.audit.OAuth2AuditLog) ArrayList(java.util.ArrayList) URI(java.net.URI) VERIFICATION_URI(io.jans.as.model.authorize.DeviceAuthorizationResponseParam.VERIFICATION_URI) JSONException(org.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) DeviceAuthorizationStatus(io.jans.as.server.model.common.DeviceAuthorizationStatus) Client(io.jans.as.common.model.registration.Client) SessionClient(io.jans.as.server.model.session.SessionClient)

Example 3 with Client

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

the class BackchannelAuthorizeRestWebServiceImpl method requestBackchannelAuthorizationPost.

@Override
public Response requestBackchannelAuthorizationPost(String clientId, String scope, String clientNotificationToken, String acrValues, String loginHintToken, String idTokenHint, String loginHint, String bindingMessage, String userCodeParam, Integer requestedExpiry, String request, String requestUri, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    // it may be encoded
    scope = ServerUtil.urlDecode(scope);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.BACKCHANNEL_AUTHENTICATION);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setScope(scope);
    // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final,
    // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
    log.debug("Attempting to request backchannel authorization: " + "clientId = {}, scope = {}, clientNotificationToken = {}, acrValues = {}, loginHintToken = {}, " + "idTokenHint = {}, loginHint = {}, bindingMessage = {}, userCodeParam = {}, requestedExpiry = {}, " + "request= {}", clientId, scope, clientNotificationToken, acrValues, loginHintToken, idTokenHint, loginHint, bindingMessage, userCodeParam, requestedExpiry, request);
    log.debug("Attempting to request backchannel authorization: " + "isSecure = {}", securityContext.isSecure());
    errorResponseFactory.validateComponentEnabled(ComponentType.CIBA);
    Response.ResponseBuilder builder = Response.ok();
    SessionClient sessionClient = identity.getSessionClient();
    Client client = null;
    if (sessionClient != null) {
        client = sessionClient.getClient();
    }
    if (client == null) {
        // 401
        builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_CLIENT));
        return builder.build();
    }
    if (!cibaRequestService.hasCibaCompatibility(client)) {
        // 401
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    List<String> scopes = new ArrayList<>();
    if (StringHelper.isNotEmpty(scope)) {
        Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
        scopes.addAll(grantedScopes);
    }
    JwtAuthorizationRequest jwtRequest = null;
    if (StringUtils.isNotBlank(request) || StringUtils.isNotBlank(requestUri)) {
        jwtRequest = JwtAuthorizationRequest.createJwtRequest(request, requestUri, client, null, cryptoProvider, appConfiguration);
        if (jwtRequest == null) {
            log.error("The JWT couldn't be processed");
            // 400
            builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
            builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
            throw new WebApplicationException(builder.build());
        }
        authorizeRestWebServiceValidator.validateCibaRequestObject(jwtRequest, client.getClientId());
        // JWT wins
        if (!jwtRequest.getScopes().isEmpty()) {
            scopes.addAll(scopeChecker.checkScopesPolicy(client, jwtRequest.getScopes()));
        }
        if (StringUtils.isNotBlank(jwtRequest.getClientNotificationToken())) {
            clientNotificationToken = jwtRequest.getClientNotificationToken();
        }
        if (StringUtils.isNotBlank(jwtRequest.getAcrValues())) {
            acrValues = jwtRequest.getAcrValues();
        }
        if (StringUtils.isNotBlank(jwtRequest.getLoginHintToken())) {
            loginHintToken = jwtRequest.getLoginHintToken();
        }
        if (StringUtils.isNotBlank(jwtRequest.getIdTokenHint())) {
            idTokenHint = jwtRequest.getIdTokenHint();
        }
        if (StringUtils.isNotBlank(jwtRequest.getLoginHint())) {
            loginHint = jwtRequest.getLoginHint();
        }
        if (StringUtils.isNotBlank(jwtRequest.getBindingMessage())) {
            bindingMessage = jwtRequest.getBindingMessage();
        }
        if (StringUtils.isNotBlank(jwtRequest.getUserCode())) {
            userCodeParam = jwtRequest.getUserCode();
        }
        if (jwtRequest.getRequestedExpiry() != null) {
            requestedExpiry = jwtRequest.getRequestedExpiry();
        } else if (jwtRequest.getExp() != null) {
            requestedExpiry = Math.toIntExact(jwtRequest.getExp() - System.currentTimeMillis() / 1000);
        }
    }
    if (appConfiguration.isFapi() && jwtRequest == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    User user = null;
    try {
        if (Strings.isNotBlank(loginHint)) {
            // login_hint
            user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), loginHint);
        } else if (Strings.isNotBlank(idTokenHint)) {
            // id_token_hint
            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
            if (authorizationGrant == null) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            user = authorizationGrant.getUser();
        }
        if (Strings.isNotBlank(loginHintToken)) {
            // login_hint_token
            Jwt jwt = Jwt.parse(loginHintToken);
            SignatureAlgorithm algorithm = jwt.getHeader().getSignatureAlgorithm();
            String keyId = jwt.getHeader().getKeyId();
            if (algorithm == null || Strings.isBlank(keyId)) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            boolean validSignature = false;
            if (algorithm.getFamily() == AlgorithmFamily.RSA) {
                RSAPublicKey publicKey = JwkClient.getRSAPublicKey(client.getJwksUri(), keyId);
                RSASigner rsaSigner = new RSASigner(algorithm, publicKey);
                validSignature = rsaSigner.validate(jwt);
            } else if (algorithm.getFamily() == AlgorithmFamily.EC) {
                ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(client.getJwksUri(), keyId);
                ECDSASigner ecdsaSigner = new ECDSASigner(algorithm, publicKey);
                validSignature = ecdsaSigner.validate(jwt);
            }
            if (!validSignature) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            JSONObject subject = jwt.getClaims().getClaimAsJSON("subject");
            if (subject == null || !subject.has("subject_type") || !subject.has(subject.getString("subject_type"))) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            String subjectTypeKey = subject.getString("subject_type");
            String subjectTypeValue = subject.getString(subjectTypeKey);
            user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), subjectTypeValue);
        }
    } catch (InvalidJwtException e) {
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        log.error(e.getMessage(), e);
    }
    if (user == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
        return builder.build();
    }
    try {
        String userCode = (String) user.getAttribute("jansBackchannelUsrCode", true, false);
        DefaultErrorResponse cibaAuthorizeParamsValidation = cibaAuthorizeParamsValidatorService.validateParams(scopes, clientNotificationToken, client.getBackchannelTokenDeliveryMode(), loginHintToken, idTokenHint, loginHint, bindingMessage, client.getBackchannelUserCodeParameter(), userCodeParam, userCode, requestedExpiry);
        if (cibaAuthorizeParamsValidation != null) {
            builder = Response.status(cibaAuthorizeParamsValidation.getStatus());
            builder.entity(errorResponseFactory.errorAsJson(cibaAuthorizeParamsValidation.getType(), cibaAuthorizeParamsValidation.getReason()));
            return builder.build();
        }
        String deviceRegistrationToken = (String) user.getAttribute("jansBackchannelDeviceRegistrationTkn", true, false);
        if (deviceRegistrationToken == null) {
            // 401
            builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
            builder.entity(errorResponseFactory.getErrorAsJson(UNAUTHORIZED_END_USER_DEVICE));
            return builder.build();
        }
        int expiresIn = requestedExpiry != null ? requestedExpiry : appConfiguration.getBackchannelAuthenticationResponseExpiresIn();
        Integer interval = client.getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PUSH ? null : appConfiguration.getBackchannelAuthenticationResponseInterval();
        long currentTime = new Date().getTime();
        CibaRequestCacheControl cibaRequestCacheControl = new CibaRequestCacheControl(user, client, expiresIn, scopes, clientNotificationToken, bindingMessage, currentTime, acrValues);
        cibaRequestService.save(cibaRequestCacheControl, expiresIn);
        String authReqId = cibaRequestCacheControl.getAuthReqId();
        // Notify End-User to obtain Consent/Authorization
        cibaEndUserNotificationService.notifyEndUser(cibaRequestCacheControl.getScopesAsString(), cibaRequestCacheControl.getAcrValues(), authReqId, deviceRegistrationToken);
        builder.entity(getJSONObject(authReqId, expiresIn, interval).toString(4).replace("\\/", "/"));
        builder.type(MediaType.APPLICATION_JSON_TYPE);
        builder.cacheControl(ServerUtil.cacheControl(true, false));
    } catch (JSONException e) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        log.error(e.getMessage(), e);
    } catch (InvalidClaimException e) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) User(io.jans.as.common.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(io.jans.as.server.model.session.SessionClient) OAuth2AuditLog(io.jans.as.server.model.audit.OAuth2AuditLog) ArrayList(java.util.ArrayList) CibaRequestCacheControl(io.jans.as.server.model.common.CibaRequestCacheControl) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) InvalidClaimException(io.jans.as.model.exception.InvalidClaimException) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) JwtAuthorizationRequest(io.jans.as.server.model.authorize.JwtAuthorizationRequest) JwkClient(io.jans.as.client.JwkClient) Client(io.jans.as.common.model.registration.Client) SessionClient(io.jans.as.server.model.session.SessionClient) DefaultErrorResponse(io.jans.as.model.error.DefaultErrorResponse) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) ECDSAPublicKey(io.jans.as.model.crypto.signature.ECDSAPublicKey) ECDSASigner(io.jans.as.model.jws.ECDSASigner) Jwt(io.jans.as.model.jwt.Jwt) JSONException(org.json.JSONException) Date(java.util.Date) Response(javax.ws.rs.core.Response) DefaultErrorResponse(io.jans.as.model.error.DefaultErrorResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONObject(org.json.JSONObject)

Example 4 with Client

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

the class AuthenticationFilter method processBasicAuth.

private void processBasicAuth(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) {
    boolean requireAuth = true;
    try {
        String header = servletRequest.getHeader(Constants.AUTHORIZATION);
        if (tokenService.isBasicAuthToken(header)) {
            String base64Token = tokenService.getBasicToken(header);
            String token = new String(Base64.decodeBase64(base64Token), StandardCharsets.UTF_8);
            String username = "";
            String password = "";
            int delim = token.indexOf(":");
            if (delim != -1) {
                // Jans Auth #677 URL decode the username and password
                username = URLDecoder.decode(token.substring(0, delim), Util.UTF8_STRING_ENCODING);
                password = URLDecoder.decode(token.substring(delim + 1), Util.UTF8_STRING_ENCODING);
            }
            requireAuth = !StringHelper.equals(username, identity.getCredentials().getUsername()) || !identity.isLoggedIn();
            // and user isn't authenticated
            if (requireAuth && !username.equals(identity.getCredentials().getUsername()) || !identity.isLoggedIn()) {
                identity.getCredentials().setUsername(username);
                identity.getCredentials().setPassword(password);
                if (servletRequest.getRequestURI().endsWith("/token") || servletRequest.getRequestURI().endsWith("/revoke") || servletRequest.getRequestURI().endsWith("/revoke_session") || servletRequest.getRequestURI().endsWith("/userinfo") || servletRequest.getRequestURI().endsWith("/bc-authorize") || servletRequest.getRequestURI().endsWith("/par") || servletRequest.getRequestURI().endsWith("/device_authorization")) {
                    Client client = clientService.getClient(username);
                    if (client == null || io.jans.as.model.common.AuthenticationMethod.CLIENT_SECRET_BASIC != client.getAuthenticationMethod()) {
                        throw new Exception("The Token Authentication Method is not valid.");
                    }
                    requireAuth = !authenticator.authenticateClient(servletRequest);
                } else {
                    requireAuth = !authenticator.authenticateUser(servletRequest);
                }
            }
        }
        if (!requireAuth) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    } catch (Exception ex) {
        log.info("Basic authentication failed", ex);
    }
    if (requireAuth && !identity.isLoggedIn()) {
        sendError(servletResponse);
    }
}
Also used : Client(io.jans.as.common.model.registration.Client) ServletException(javax.servlet.ServletException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException)

Example 5 with Client

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

the class AuthenticationFilter method processPostAuth.

private void processPostAuth(ClientFilterService clientFilterService, HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain, boolean tokenEndpoint) {
    try {
        String clientId = "";
        String clientSecret = "";
        boolean isExistUserPassword = false;
        if (StringHelper.isNotEmpty(servletRequest.getParameter(Constants.CLIENT_ID)) && StringHelper.isNotEmpty(servletRequest.getParameter("client_secret"))) {
            clientId = servletRequest.getParameter(Constants.CLIENT_ID);
            clientSecret = servletRequest.getParameter("client_secret");
            isExistUserPassword = true;
        }
        log.trace("isExistUserPassword: {}", isExistUserPassword);
        boolean requireAuth = !StringHelper.equals(clientId, identity.getCredentials().getUsername()) || !identity.isLoggedIn();
        log.debug("requireAuth: '{}'", requireAuth);
        if (requireAuth) {
            if (isExistUserPassword) {
                Client client = clientService.getClient(clientId);
                if (client != null && io.jans.as.model.common.AuthenticationMethod.CLIENT_SECRET_POST == client.getAuthenticationMethod()) {
                    // Identity.username and user isn't authenticated
                    if (!clientId.equals(identity.getCredentials().getUsername()) || !identity.isLoggedIn()) {
                        identity.logout();
                        identity.getCredentials().setUsername(clientId);
                        identity.getCredentials().setPassword(clientSecret);
                        requireAuth = !authenticator.authenticateClient(servletRequest);
                    } else {
                        authenticator.configureSessionClient(client);
                    }
                }
            } else if (Boolean.TRUE.equals(appConfiguration.getClientAuthenticationFiltersEnabled())) {
                String clientDn = clientFilterService.processAuthenticationFilters(servletRequest.getParameterMap());
                if (clientDn != null) {
                    Client client = clientService.getClientByDn(clientDn);
                    identity.logout();
                    identity.getCredentials().setUsername(client.getClientId());
                    identity.getCredentials().setPassword(null);
                    requireAuth = !authenticator.authenticateClient(servletRequest, true);
                }
            } else if (tokenEndpoint) {
                Client client = clientService.getClient(servletRequest.getParameter(Constants.CLIENT_ID));
                if (client != null && client.getAuthenticationMethod() == AuthenticationMethod.NONE) {
                    identity.logout();
                    identity.getCredentials().setUsername(client.getClientId());
                    identity.getCredentials().setPassword(null);
                    requireAuth = !authenticator.authenticateClient(servletRequest, true);
                }
            }
        }
        if (!requireAuth) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (!identity.isLoggedIn()) {
            sendError(servletResponse);
        }
    } catch (Exception ex) {
        log.error("Post authentication failed.", ex);
    }
}
Also used : Client(io.jans.as.common.model.registration.Client) ServletException(javax.servlet.ServletException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException)

Aggregations

Client (io.jans.as.common.model.registration.Client)70 WebApplicationException (javax.ws.rs.WebApplicationException)20 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)12 JSONObject (org.json.JSONObject)12 Test (org.testng.annotations.Test)12 User (io.jans.as.common.model.common.User)11 BaseComponentTest (io.jans.as.server.BaseComponentTest)10 Calendar (java.util.Calendar)10 GregorianCalendar (java.util.GregorianCalendar)10 IOException (java.io.IOException)9 OAuth2AuditLog (io.jans.as.server.model.audit.OAuth2AuditLog)8 AuthorizationGrant (io.jans.as.server.model.common.AuthorizationGrant)8 ExecutionContext (io.jans.as.server.model.common.ExecutionContext)8 JSONException (org.json.JSONException)8 Jwt (io.jans.as.model.jwt.Jwt)7 Response (javax.ws.rs.core.Response)7 SessionClient (io.jans.as.server.model.session.SessionClient)6 ProtectedApi (io.jans.configapi.core.rest.ProtectedApi)6 ServletException (javax.servlet.ServletException)6 SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)5