Search in sources :

Example 1 with AuthorizationGrant

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

the class LogoutAction method processExternalAuthenticatorLogOut.

private ExternalLogoutResult processExternalAuthenticatorLogOut(SessionId sessionId) {
    if ((sessionId != null) && sessionId.getSessionAttributes().containsKey(EXTERNAL_LOGOUT)) {
        log.debug("Detected callback from external system. Resuming logout.");
        return ExternalLogoutResult.SUCCESS;
    }
    AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
    if (authorizationGrant == null) {
        Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
        if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
            authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
        }
    }
    if ((authorizationGrant == null) && (sessionId == null)) {
        return ExternalLogoutResult.FAILURE;
    }
    String acrValues;
    if (authorizationGrant == null) {
        acrValues = sessionIdService.getAcr(sessionId);
    } else {
        acrValues = authorizationGrant.getAcrValues();
    }
    boolean isExternalAuthenticatorLogoutPresent = StringHelper.isNotEmpty(acrValues);
    if (isExternalAuthenticatorLogoutPresent) {
        log.debug("Attemptinmg to execute logout method of '{}' external authenticator.", acrValues);
        CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.getCustomScriptConfigurationByName(acrValues);
        if (customScriptConfiguration == null) {
            log.error("Failed to get ExternalAuthenticatorConfiguration. acr_values: {}", acrValues);
            return ExternalLogoutResult.FAILURE;
        } else {
            boolean scriptExternalLogoutResult = externalAuthenticationService.executeExternalLogout(customScriptConfiguration, null);
            ExternalLogoutResult externalLogoutResult = scriptExternalLogoutResult ? ExternalLogoutResult.SUCCESS : ExternalLogoutResult.FAILURE;
            final String userDn = sessionId != null ? sessionId.getUserDn() : "";
            final String sId = sessionId != null ? sessionId.getId() : "";
            log.debug("Logout result is '{}' for session '{}', userDn: '{}'", externalLogoutResult, sId, userDn);
            int apiVersion = externalAuthenticationService.executeExternalGetApiVersion(customScriptConfiguration);
            if (apiVersion < 3) {
                // Not support redirect to external system at logout
                return externalLogoutResult;
            }
            log.trace("According to API version script supports logout redirects");
            String logoutExternalUrl = externalAuthenticationService.getLogoutExternalUrl(customScriptConfiguration, null);
            log.debug("External logout result is '{}' for user '{}'", logoutExternalUrl, userDn);
            if (StringHelper.isEmpty(logoutExternalUrl)) {
                return externalLogoutResult;
            }
            // Store in session parameters needed to call end_session
            try {
                storeLogoutParametersInSession(sessionId);
            } catch (IOException ex) {
                log.debug("Failed to persist logout parameters in session", ex);
                return ExternalLogoutResult.FAILURE;
            }
            // Redirect to external URL
            facesService.redirectToExternalURL(logoutExternalUrl);
            return ExternalLogoutResult.REDIRECT;
        }
    } else {
        return ExternalLogoutResult.SUCCESS;
    }
}
Also used : IOException(java.io.IOException) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 2 with AuthorizationGrant

use of io.jans.as.server.model.common.AuthorizationGrant 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 3 with AuthorizationGrant

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

the class StatWS method validateAuthorization.

private void validateAuthorization(String authorization) {
    log.trace("Validating authorization: {}", authorization);
    AuthorizationGrant grant = tokenService.getAuthorizationGrant(authorization);
    if (grant == null) {
        log.trace("Unable to find token by authorization: {}", authorization);
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Can't find grant for authorization.");
    }
    final AbstractToken accessToken = grant.getAccessToken(tokenService.getToken(authorization));
    if (accessToken == null) {
        log.trace("Unable to find token by authorization: {}", authorization);
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Can't find access token.");
    }
    if (accessToken.isExpired()) {
        log.trace("Access Token is expired: {}", accessToken.getCode());
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Token expired.");
    }
    if (!grant.getScopesAsString().contains(appConfiguration.getStatAuthorizationScope())) {
        log.trace("Access Token does NOT have '{}' scope which is required to call Statistic Endpoint.", appConfiguration.getStatAuthorizationScope());
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, appConfiguration.getStatAuthorizationScope() + " scope is required for token.");
    }
}
Also used : AbstractToken(io.jans.as.server.model.common.AbstractToken) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant)

Example 4 with AuthorizationGrant

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

the class UmaResourceRegistrationWS method putResourceImpl.

private Response putResourceImpl(Response.Status status, String authorization, String rsid, io.jans.as.model.uma.UmaResource resource) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("putResourceImpl, rsid: {}, status: {}", escapeLog(rsid), status.name());
    }
    errorResponseFactory.validateComponentEnabled(ComponentType.UMA);
    AuthorizationGrant authorizationGrant = umaValidationService.assertHasProtectionScope(authorization);
    umaValidationService.validateResource(resource);
    String userDn = authorizationGrant.getUserDn();
    String clientDn = authorizationGrant.getClientDn();
    io.jans.as.model.uma.persistence.UmaResource ldapUpdatedResource;
    if (status == Response.Status.CREATED) {
        ldapUpdatedResource = addResource(rsid, resource, userDn, clientDn);
    } else {
        umaValidationService.validateRestrictedByClient(clientDn, rsid);
        ldapUpdatedResource = updateResource(rsid, resource);
    }
    io.jans.as.model.uma.UmaResourceResponse response = new io.jans.as.model.uma.UmaResourceResponse();
    response.setId(ldapUpdatedResource.getId());
    return Response.status(status).type(MediaType.APPLICATION_JSON_TYPE).entity(ServerUtil.asJson(response)).build();
}
Also used : AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant)

Example 5 with AuthorizationGrant

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

the class UmaResourceRegistrationWS method getResourceList.

/**
 * Gets resource set lists.
 * ATTENTION: "scope" is parameter added by gluu to have additional filtering.
 * There is no such parameter in UMA specification.
 *
 * @param authorization authorization
 * @param scope         scope of resource set for additional filtering, can blank string.
 * @return resource set ids.
 */
@GET
@Produces({ UmaConstants.JSON_MEDIA_TYPE })
public List<String> getResourceList(@HeaderParam("Authorization") String authorization, @QueryParam("scope") String scope) {
    try {
        log.trace("Getting list of resource descriptions.");
        errorResponseFactory.validateComponentEnabled(ComponentType.UMA);
        final AuthorizationGrant authorizationGrant = umaValidationService.assertHasProtectionScope(authorization);
        final String clientDn = authorizationGrant.getClientDn();
        final List<io.jans.as.model.uma.persistence.UmaResource> ldapResources = resourceService.getResourcesByAssociatedClient(clientDn);
        final List<String> result = new ArrayList<>(ldapResources.size());
        for (io.jans.as.model.uma.persistence.UmaResource ldapResource : ldapResources) {
            // if scope parameter is not null then filter by it, otherwise just add to result
            if (StringUtils.isNotBlank(scope)) {
                final List<String> scopeUrlsByDns = umaScopeService.getScopeIdsByDns(ldapResource.getScopes());
                if (scopeUrlsByDns != null && scopeUrlsByDns.contains(scope)) {
                    result.add(ldapResource.getId());
                }
            } else {
                result.add(ldapResource.getId());
            }
        }
        return result;
    } catch (Exception ex) {
        log.error("Exception happened on getResourceList()", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        } else {
            throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, io.jans.as.model.uma.UmaErrorResponseType.SERVER_ERROR, ex.getMessage());
        }
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

AuthorizationGrant (io.jans.as.server.model.common.AuthorizationGrant)31 WebApplicationException (javax.ws.rs.WebApplicationException)16 IOException (java.io.IOException)10 AbstractToken (io.jans.as.server.model.common.AbstractToken)9 Client (io.jans.as.common.model.registration.Client)8 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)7 SessionId (io.jans.as.server.model.common.SessionId)6 OAuth2AuditLog (io.jans.as.server.model.audit.OAuth2AuditLog)5 Response (javax.ws.rs.core.Response)5 JSONObject (org.json.JSONObject)5 User (io.jans.as.common.model.common.User)4 JSONWebKey (io.jans.as.model.jwk.JSONWebKey)4 Jwt (io.jans.as.model.jwt.Jwt)4 ServletException (javax.servlet.ServletException)4 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 GrantType (io.jans.as.model.common.GrantType)3 SessionClient (io.jans.as.server.model.session.SessionClient)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 JSONArray (org.json.JSONArray)3