Search in sources :

Example 1 with RedirectUri

use of io.jans.as.common.util.RedirectUri in project jans by JanssenProject.

the class AuthorizeRestWebServiceValidator method validate.

public void validate(List<io.jans.as.model.common.ResponseType> responseTypes, List<Prompt> prompts, String nonce, String state, String redirectUri, HttpServletRequest httpRequest, Client client, io.jans.as.model.common.ResponseMode responseMode) {
    if (!AuthorizeParamsValidator.validateParams(responseTypes, prompts, nonce, appConfiguration.isFapi(), responseMode)) {
        if (redirectUri != null && redirectionUriService.validateRedirectionUri(client, redirectUri) != null) {
            RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
            redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST, state));
            throw new WebApplicationException(RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest).build());
        } else {
            throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST.getStatusCode()).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, state, "Invalid redirect uri.")).build());
        }
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) RedirectUri(io.jans.as.common.util.RedirectUri)

Example 2 with RedirectUri

use of io.jans.as.common.util.RedirectUri in project jans by JanssenProject.

the class ParRestWebService method requestPushedAuthorizationRequest.

@POST
@Produces({ MediaType.APPLICATION_JSON })
public Response requestPushedAuthorizationRequest(@FormParam("scope") String scope, @FormParam("response_type") String responseType, @FormParam("client_id") String clientId, @FormParam("redirect_uri") String redirectUri, @FormParam("state") String state, @FormParam("response_mode") String responseMode, @FormParam("nonce") String nonce, @FormParam("display") String display, @FormParam("prompt") String prompt, @FormParam("max_age") Integer maxAge, @FormParam("ui_locales") String uiLocales, @FormParam("id_token_hint") String idTokenHint, @FormParam("login_hint") String loginHint, @FormParam("acr_values") String acrValuesStr, @FormParam("amr_values") String amrValuesStr, @FormParam("request") String request, @FormParam("request_uri") String requestUri, @FormParam("session_id") String sessionId, @FormParam("origin_headers") String originHeaders, @FormParam("code_challenge") String codeChallenge, @FormParam("code_challenge_method") String codeChallengeMethod, @FormParam("nbf") String nbf, @FormParam(AuthorizeRequestParam.CUSTOM_RESPONSE_HEADERS) String customResponseHeaders, @FormParam("claims") String claims, @Context HttpServletRequest httpRequest, @Context HttpServletResponse httpResponse, @Context SecurityContext securityContext) {
    try {
        errorResponseFactory.validateComponentEnabled(ComponentType.PAR);
        // it may be encoded
        scope = ServerUtil.urlDecode(scope);
        String tokenBindingHeader = httpRequest.getHeader("Sec-Token-Binding");
        // ATTENTION : please do not add more parameter in this debug method because it will not work with framework
        // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
        log.debug("Attempting to request PAR: " + "responseType = {}, clientId = {}, scope = {}, redirectUri = {}, nonce = {}, " + "state = {}, request = {}, isSecure = {}, sessionId = {}", responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(), sessionId);
        log.debug("Attempting to request PAR: " + "acrValues = {}, amrValues = {}, originHeaders = {}, codeChallenge = {}, codeChallengeMethod = {}, " + "customRespHeaders = {}, claims = {}, tokenBindingHeader = {}", acrValuesStr, amrValuesStr, originHeaders, codeChallenge, codeChallengeMethod, customResponseHeaders, claims, tokenBindingHeader);
        parValidator.validatePkce(codeChallenge, codeChallengeMethod, state);
        List<ResponseType> responseTypes = ResponseType.fromString(responseType, " ");
        ResponseMode responseModeObj = ResponseMode.getByValue(responseMode);
        Jwt requestObject = Jwt.parseSilently(request);
        clientId = getClientId(clientId, requestObject);
        Client client = authorizeRestWebServiceValidator.validateClient(clientId, state, true);
        redirectUri = getRedirectUri(redirectUri, requestObject);
        redirectUri = authorizeRestWebServiceValidator.validateRedirectUri(client, redirectUri, state, null, httpRequest, AuthorizeErrorResponseType.INVALID_REQUEST);
        RedirectUriResponse redirectUriResponse = new RedirectUriResponse(new RedirectUri(redirectUri, responseTypes, responseModeObj), state, httpRequest, errorResponseFactory);
        redirectUriResponse.setFapiCompatible(appConfiguration.isFapi());
        parValidator.validateRequestUriIsAbsent(requestUri);
        final Integer parLifetime = client.getAttributes().getParLifetime();
        final Par par = new Par();
        par.setDeletable(true);
        par.setTtl(parLifetime);
        par.setExpirationDate(Util.createExpirationDate(parLifetime));
        par.getAttributes().setScope(scope);
        par.getAttributes().setNbf(Util.parseIntegerSilently(nbf));
        par.getAttributes().setResponseType(responseType);
        par.getAttributes().setClientId(clientId);
        par.getAttributes().setRedirectUri(redirectUri);
        par.getAttributes().setState(state);
        par.getAttributes().setResponseMode(responseMode);
        par.getAttributes().setNonce(nonce);
        par.getAttributes().setDisplay(display);
        par.getAttributes().setPrompt(prompt);
        par.getAttributes().setMaxAge(maxAge);
        par.getAttributes().setUiLocales(uiLocales);
        par.getAttributes().setIdTokenHint(idTokenHint);
        par.getAttributes().setLoginHint(loginHint);
        par.getAttributes().setAcrValuesStr(acrValuesStr);
        par.getAttributes().setAmrValuesStr(amrValuesStr);
        par.getAttributes().setRequest(request);
        par.getAttributes().setRequestUri(requestUri);
        par.getAttributes().setSessionId(sessionId);
        par.getAttributes().setOriginHeaders(originHeaders);
        par.getAttributes().setCodeChallenge(codeChallenge);
        par.getAttributes().setCodeChallengeMethod(codeChallengeMethod);
        par.getAttributes().setCustomResponseHeaders(customResponseHeaders);
        par.getAttributes().setClaims(claims);
        par.getAttributes().setCustomParameters(requestParameterService.getCustomParameters(QueryStringDecoder.decode(httpRequest.getQueryString())));
        parValidator.validateRequestObject(redirectUriResponse, par, client);
        authorizeRestWebServiceValidator.validatePkce(par.getAttributes().getCodeChallenge(), redirectUriResponse);
        parService.persist(par);
        ParResponse parResponse = new ParResponse();
        parResponse.setRequestUri(ParService.toOutsideId(par.getId()));
        // set it to TTL instead of lifetime because TTL can be updated during request object validation
        parResponse.setExpiresIn(par.getTtl());
        final String responseAsString = ServerUtil.asJson(parResponse);
        log.debug("Created PAR {}", responseAsString);
        return Response.status(Response.Status.CREATED).entity(responseAsString).type(MediaType.APPLICATION_JSON_TYPE).build();
    } catch (WebApplicationException e) {
        if (e.getResponse().getStatus() == Response.Status.FOUND.getStatusCode()) {
            throw errorResponseFactory.createBadRequestException(createErrorResponseFromRedirectErrorUri(e.getResponse().getLocation()));
        }
        if (log.isErrorEnabled())
            log.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON_TYPE).build();
    }
}
Also used : Par(io.jans.as.persistence.model.Par) WebApplicationException(javax.ws.rs.WebApplicationException) Jwt(io.jans.as.model.jwt.Jwt) RedirectUriResponse(io.jans.as.server.service.RedirectUriResponse) RedirectUri(io.jans.as.common.util.RedirectUri) WebApplicationException(javax.ws.rs.WebApplicationException) AuthorizeErrorResponseType(io.jans.as.model.authorize.AuthorizeErrorResponseType) ResponseType(io.jans.as.model.common.ResponseType) ResponseMode(io.jans.as.model.common.ResponseMode) Client(io.jans.as.common.model.registration.Client) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 3 with RedirectUri

use of io.jans.as.common.util.RedirectUri in project jans by JanssenProject.

the class ParRestWebService method createErrorResponseFromRedirectErrorUri.

@NotNull
private ErrorResponse createErrorResponseFromRedirectErrorUri(@NotNull URI location) {
    final RedirectUri locationRedirect = new RedirectUri(location.toString());
    locationRedirect.parseQueryString(location.getQuery());
    final ErrorResponse response = new ErrorResponse();
    String error = locationRedirect.getResponseParameter("error");
    String errorDescription = locationRedirect.getResponseParameter("error_description");
    errorDescription = Optional.ofNullable(errorDescription).map(description -> Optional.ofNullable(ThreadContext.get(Constants.CORRELATION_ID_HEADER)).map(id -> description.concat(" CorrelationId: " + id)).orElse(description)).orElse(null);
    response.setErrorCode(error);
    response.setErrorDescription(errorDescription);
    return response;
}
Also used : RedirectUri(io.jans.as.common.util.RedirectUri) ErrorResponse(io.jans.as.model.error.ErrorResponse) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with RedirectUri

use of io.jans.as.common.util.RedirectUri in project jans by JanssenProject.

the class CIBAEndUserNotificationService method notifyEndUserUsingFCM.

/**
 * Method responsible to send notifications to the end user using Firebase Cloud Messaging.
 *
 * @param deviceRegistrationToken Device already registered.
 * @param scope                   Scope of the authorization request
 * @param acrValues               Acr values used to the authorzation request
 * @param authReqId               Authentication request id.
 */
private void notifyEndUserUsingFCM(String scope, String acrValues, String authReqId, String deviceRegistrationToken) {
    String clientId = appConfiguration.getBackchannelClientId();
    String redirectUri = appConfiguration.getBackchannelRedirectUri();
    String url = appConfiguration.getCibaEndUserNotificationConfig().getNotificationUrl();
    String key = cibaEncryptionService.decrypt(appConfiguration.getCibaEndUserNotificationConfig().getNotificationKey(), true);
    String title = "Jans Auth Authentication Request";
    String body = "Client Initiated Backchannel Authentication (CIBA)";
    RedirectUri authorizationRequestUri = new RedirectUri(appConfiguration.getAuthorizationEndpoint());
    authorizationRequestUri.addResponseParameter(CLIENT_ID, clientId);
    authorizationRequestUri.addResponseParameter(RESPONSE_TYPE, "id_token");
    authorizationRequestUri.addResponseParameter(SCOPE, scope);
    authorizationRequestUri.addResponseParameter(ACR_VALUES, acrValues);
    authorizationRequestUri.addResponseParameter(REDIRECT_URI, redirectUri);
    authorizationRequestUri.addResponseParameter(STATE, UUID.randomUUID().toString());
    authorizationRequestUri.addResponseParameter(NONCE, UUID.randomUUID().toString());
    authorizationRequestUri.addResponseParameter(PROMPT, "consent");
    authorizationRequestUri.addResponseParameter(AUTH_REQ_ID, authReqId);
    String clickAction = authorizationRequestUri.toString();
    FirebaseCloudMessagingRequest firebaseCloudMessagingRequest = new FirebaseCloudMessagingRequest(key, deviceRegistrationToken, title, body, clickAction);
    FirebaseCloudMessagingClient firebaseCloudMessagingClient = new FirebaseCloudMessagingClient(url);
    firebaseCloudMessagingClient.setRequest(firebaseCloudMessagingRequest);
    FirebaseCloudMessagingResponse firebaseCloudMessagingResponse = firebaseCloudMessagingClient.exec();
    log.debug("CIBA: firebase cloud messaging result status {}", firebaseCloudMessagingResponse.getStatus());
}
Also used : FirebaseCloudMessagingClient(io.jans.as.client.ciba.fcm.FirebaseCloudMessagingClient) FirebaseCloudMessagingRequest(io.jans.as.client.ciba.fcm.FirebaseCloudMessagingRequest) RedirectUri(io.jans.as.common.util.RedirectUri) FirebaseCloudMessagingResponse(io.jans.as.client.ciba.fcm.FirebaseCloudMessagingResponse)

Example 5 with RedirectUri

use of io.jans.as.common.util.RedirectUri in project jans by JanssenProject.

the class AuthorizeService method permissionDenied.

public void permissionDenied(final SessionId session) {
    log.trace("permissionDenied");
    invalidateSessionCookiesIfNeeded();
    if (session == null) {
        authenticationFailedSessionInvalid();
        return;
    }
    String baseRedirectUri = session.getSessionAttributes().get(AuthorizeRequestParam.REDIRECT_URI);
    String state = session.getSessionAttributes().get(AuthorizeRequestParam.STATE);
    ResponseMode responseMode = ResponseMode.fromString(session.getSessionAttributes().get(AuthorizeRequestParam.RESPONSE_MODE));
    List<ResponseType> responseType = ResponseType.fromString(session.getSessionAttributes().get(AuthorizeRequestParam.RESPONSE_TYPE), " ");
    RedirectUri redirectUri = new RedirectUri(baseRedirectUri, responseType, responseMode);
    redirectUri.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.ACCESS_DENIED, state));
    // CIBA
    Map<String, String> sessionAttribute = requestParameterService.getAllowedParameters(session.getSessionAttributes());
    if (sessionAttribute.containsKey(AuthorizeRequestParam.AUTH_REQ_ID)) {
        String authReqId = sessionAttribute.get(AuthorizeRequestParam.AUTH_REQ_ID);
        CibaRequestCacheControl request = cibaRequestService.getCibaRequest(authReqId);
        if (request != null && request.getClient() != null) {
            if (request.getStatus() == CibaRequestStatus.PENDING) {
                cibaRequestService.removeCibaRequest(authReqId);
            }
            switch(request.getClient().getBackchannelTokenDeliveryMode()) {
                case POLL:
                    request.setStatus(CibaRequestStatus.DENIED);
                    request.setTokensDelivered(false);
                    cibaRequestService.update(request);
                    break;
                case PING:
                    request.setStatus(CibaRequestStatus.DENIED);
                    request.setTokensDelivered(false);
                    cibaRequestService.update(request);
                    cibaPingCallbackService.pingCallback(request.getAuthReqId(), request.getClient().getBackchannelClientNotificationEndpoint(), request.getClientNotificationToken());
                    break;
                case PUSH:
                    cibaPushErrorService.pushError(request.getAuthReqId(), request.getClient().getBackchannelClientNotificationEndpoint(), request.getClientNotificationToken(), PushErrorResponseType.ACCESS_DENIED, "The end-user denied the authorization request.");
                    break;
            }
        }
    }
    if (sessionAttribute.containsKey(DeviceAuthorizationService.SESSION_USER_CODE)) {
        processDeviceAuthDeniedResponse(sessionAttribute);
    }
    if (responseMode == ResponseMode.JWT) {
        String clientId = session.getSessionAttributes().get(AuthorizeRequestParam.CLIENT_ID);
        Client client = clientService.getClient(clientId);
        facesService.redirectToExternalURL(createJarmRedirectUri(redirectUri, client, session));
    } else
        facesService.redirectToExternalURL(redirectUri.toString());
}
Also used : ResponseMode(io.jans.as.model.common.ResponseMode) CibaRequestCacheControl(io.jans.as.server.model.common.CibaRequestCacheControl) RedirectUri(io.jans.as.common.util.RedirectUri) Client(io.jans.as.common.model.registration.Client) PushErrorResponseType(io.jans.as.model.ciba.PushErrorResponseType) AuthorizeErrorResponseType(io.jans.as.model.authorize.AuthorizeErrorResponseType) ResponseType(io.jans.as.model.common.ResponseType)

Aggregations

RedirectUri (io.jans.as.common.util.RedirectUri)9 Client (io.jans.as.common.model.registration.Client)3 AuthorizeErrorResponseType (io.jans.as.model.authorize.AuthorizeErrorResponseType)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 ResponseMode (io.jans.as.model.common.ResponseMode)2 ResponseType (io.jans.as.model.common.ResponseType)2 Par (io.jans.as.persistence.model.Par)2 FirebaseCloudMessagingClient (io.jans.as.client.ciba.fcm.FirebaseCloudMessagingClient)1 FirebaseCloudMessagingRequest (io.jans.as.client.ciba.fcm.FirebaseCloudMessagingRequest)1 FirebaseCloudMessagingResponse (io.jans.as.client.ciba.fcm.FirebaseCloudMessagingResponse)1 User (io.jans.as.common.model.common.User)1 PushErrorResponseType (io.jans.as.model.ciba.PushErrorResponseType)1 ErrorResponse (io.jans.as.model.error.ErrorResponse)1 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)1 Jwt (io.jans.as.model.jwt.Jwt)1 JsonWebResponse (io.jans.as.model.token.JsonWebResponse)1 OAuth2AuditLog (io.jans.as.server.model.audit.OAuth2AuditLog)1 CibaRequestCacheControl (io.jans.as.server.model.common.CibaRequestCacheControl)1 AcrChangedException (io.jans.as.server.model.exception.AcrChangedException)1 InvalidRedirectUrlException (io.jans.as.server.model.exception.InvalidRedirectUrlException)1