Search in sources :

Example 1 with Parameters

use of io.gravitee.am.common.oauth2.Parameters in project gravitee-access-management by gravitee-io.

the class CibaTokenGranter method parseRequest.

@Override
protected Single<TokenRequest> parseRequest(TokenRequest tokenRequest, Client client) {
    MultiValueMap<String, String> parameters = tokenRequest.parameters();
    final String authReqId = parameters.getFirst(Parameters.AUTH_REQ_ID);
    if (isEmpty(authReqId)) {
        return Single.error(new InvalidRequestException("Missing parameter: auth_req_id"));
    }
    return super.parseRequest(tokenRequest, client).flatMap(tokenRequest1 -> authenticationRequestService.retrieve(domain, authReqId).map(cibaRequest -> {
        if (!cibaRequest.getClientId().equals(client.getClientId())) {
            logger.warn("client_id '{}' requests token using not owned authentication request '{}'", client.getId(), authReqId);
            throw new AuthenticationRequestNotFoundException("Authentication request not found");
        }
        return cibaRequest;
    }).map(cibaRequest -> {
        // set resource owner
        tokenRequest1.setSubject(cibaRequest.getSubject());
        // set original scopes
        tokenRequest1.setScopes(cibaRequest.getScopes());
        // store only the AuthenticationFlowContext.data attributes in order to simplify EL templating
        // and provide an up to date set of data if the enrichAuthFlow Policy ius used multiple time in a step
        // {#context.attributes['authFlow']['entry']}
        tokenRequest1.getContext().put(AUTH_FLOW_CONTEXT_ATTRIBUTES_KEY, emptyMap());
        return tokenRequest1;
    }));
}
Also used : InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) Collections.emptyMap(java.util.Collections.emptyMap) GrantType(io.gravitee.am.common.oauth2.GrantType) Logger(org.slf4j.Logger) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) TokenRequest(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest) Client(io.gravitee.am.model.oidc.Client) MultiValueMap(io.gravitee.common.util.MultiValueMap) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) AuthenticationRequestService(io.gravitee.am.gateway.handler.ciba.service.AuthenticationRequestService) Domain(io.gravitee.am.model.Domain) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) AbstractTokenGranter(io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter) TokenService(io.gravitee.am.gateway.handler.oauth2.service.token.TokenService) Single(io.reactivex.Single) Parameters(io.gravitee.am.common.ciba.Parameters) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) TokenRequestResolver(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequestResolver) StringUtils.isEmpty(org.springframework.util.StringUtils.isEmpty) User(io.gravitee.am.model.User) AuthenticationRequestNotFoundException(io.gravitee.am.gateway.handler.ciba.exception.AuthenticationRequestNotFoundException) AuthenticationRequestNotFoundException(io.gravitee.am.gateway.handler.ciba.exception.AuthenticationRequestNotFoundException) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException)

Example 2 with Parameters

use of io.gravitee.am.common.oauth2.Parameters in project geotoolkit by Geomatys.

the class SmlXMLBindingTest method ComponentUnmarshallMarshalingTest.

/**
 * Test simple Record Marshalling.
 *
 * @throws java.lang.Exception
 */
@Test
public void ComponentUnmarshallMarshalingTest() throws Exception {
    Unmarshaller unmarshaller = SensorMLMarshallerPool.getInstance().acquireUnmarshaller();
    InputStream is = SmlXMLBindingTest.class.getResourceAsStream("/org/geotoolkit/sml/component.xml");
    Object unmarshalled = unmarshaller.unmarshal(is);
    if (unmarshalled instanceof JAXBElement) {
        unmarshalled = ((JAXBElement) unmarshalled).getValue();
    }
    assertTrue(unmarshalled instanceof SensorML);
    SensorML result = (SensorML) unmarshalled;
    Member member = new Member();
    member.setRole("urn:x-ogx:def:sensor:OGC:detector");
    ComponentType component = new ComponentType();
    List<JAXBElement<String>> kw = new ArrayList<JAXBElement<String>>();
    kw.add(sml100Factory.createKeywordsKeywordListKeyword("piezometer"));
    kw.add(sml100Factory.createKeywordsKeywordListKeyword("geosciences"));
    kw.add(sml100Factory.createKeywordsKeywordListKeyword("point d'eau"));
    Keywords keywords = new Keywords(new KeywordList(URI.create("urn:x-brgm:def:gcmd:keywords"), kw));
    component.setKeywords(keywords);
    Classifier cl1 = new Classifier("intendedApplication", new Term("eaux souterraines", URI.create("urn:x-ogc:def:classifier:OGC:application")));
    CodeSpacePropertyType cs = new CodeSpacePropertyType("urn:x-brgm:def:GeoPoint:bss");
    Classifier cl2 = new Classifier("sensorType", new Term(cs, "Profondeur", URI.create("urn:sensor:classifier:sensorType")));
    List<Classifier> cls = new ArrayList<Classifier>();
    cls.add(cl1);
    cls.add(cl2);
    ClassifierList claList = new ClassifierList(null, cls);
    Classification classification = new Classification(claList);
    component.setClassification(classification);
    List<Identifier> identifiers = new ArrayList<Identifier>();
    cs = new CodeSpacePropertyType("urn:x-brgm:def:sensorSystem:hydras");
    Identifier id1 = new Identifier("supervisorCode", new Term(cs, "00ARGLELES_2000", URI.create("urn:x-ogc:def:identifier:OGC:modelNumber")));
    Identifier id2 = new Identifier("longName", new Term("Madofil II", URI.create("urn:x-ogc:def:identifier:OGC:longname")));
    identifiers.add(id1);
    identifiers.add(id2);
    IdentifierList identifierList = new IdentifierList(null, identifiers);
    Identification identification = new Identification(identifierList);
    component.setIdentification(identification);
    TimePeriodType period = new TimePeriodType(new TimePositionType("2004-06-01"));
    ValidTime vTime = new ValidTime(period);
    component.setValidTime(vTime);
    Capabilities capabilities = new Capabilities();
    TimeRange timeRange = new TimeRange(Arrays.asList("1987-04-23", "now"));
    DataComponentPropertyType field = new DataComponentPropertyType("periodOfData", "urn:x-brgm:def:property:periodOfData", timeRange);
    DataRecordType record = new DataRecordType("urn:x-brgm:def:property:periodOfData", Arrays.asList(field));
    JAXBElement<? extends AbstractDataRecordType> jbRecord = swe100Factory.createDataRecord(record);
    capabilities.setAbstractDataRecord(jbRecord);
    component.setCapabilities(capabilities);
    Contact contact = new Contact("urn:x-ogc:def:role:manufacturer", new ResponsibleParty("IRIS"));
    component.setContact(contact);
    Position position = new Position("conductivitePosition", "piezometer#piezoPosition");
    component.setPosition(position);
    IoComponentPropertyType io = new IoComponentPropertyType("level", new ObservableProperty("urn:x-ogc:def:phenomenon:OGC:level"));
    InputList inputList = new InputList(Arrays.asList(io));
    Inputs inputs = new Inputs(inputList);
    component.setInputs(inputs);
    IoComponentPropertyType io2 = new IoComponentPropertyType("depth", new ObservableProperty("urn:x-ogc:def:phenomenon:OGC:depth"));
    OutputList outputList = new OutputList(Arrays.asList(io2));
    Outputs outputs = new Outputs(outputList);
    component.setOutputs(outputs);
    List<DataComponentPropertyType> params = new ArrayList<DataComponentPropertyType>();
    UomPropertyType uom = new UomPropertyType(null, "urn:ogc:unit:minuts");
    QuantityType quantity1 = new QuantityType("urn:x-ogc:def:property:frequency", uom, 60.0);
    DataComponentPropertyType p1 = new DataComponentPropertyType("frequency", "urn:x-ogc:def:property:frequency", quantity1);
    params.add(p1);
    UomPropertyType uom2 = new UomPropertyType("m", null);
    QuantityType quantity2 = new QuantityType("urn:x-ogc:def:property:precision", uom2, 0.05);
    DataComponentPropertyType p2 = new DataComponentPropertyType("precision", "urn:x-ogc:def:property:precision", quantity2);
    params.add(p2);
    QuantityRange quantityRange = new QuantityRange(uom2, Arrays.asList(0.0, 10.0));
    DataComponentPropertyType p3 = new DataComponentPropertyType("validity", "urn:x-ogc:def:property:validity", quantityRange);
    params.add(p3);
    ParameterList paramList = new ParameterList(params);
    Parameters parameters = new Parameters(paramList);
    component.setParameters(parameters);
    component.setPosition(new Position("conductivitePosition", "piezometer#piezoPosition"));
    component.setName(new DefaultIdentifier("Capteur Profondeur de ARGELES"));
    member.setProcess(sml100Factory.createComponent(component));
    SensorML expectedResult = new SensorML("1.0", Arrays.asList(member));
    assertEquals(result.getMember().size(), 1);
    assertTrue(result.getMember().get(0).getProcess() != null);
    assertTrue(result.getMember().get(0).getProcess().getValue() instanceof ComponentType);
    ComponentType resultProcess = (ComponentType) result.getMember().get(0).getProcess().getValue();
    assertEquals(resultProcess.getCapabilities(), component.getCapabilities());
    assertTrue(resultProcess.getContact().size() == 1);
    assertEquals(resultProcess.getContact().get(0).getContactList(), component.getContact().get(0).getContactList());
    assertEquals(resultProcess.getContact().get(0).getResponsibleParty().getContactInfo(), component.getContact().get(0).getResponsibleParty().getContactInfo());
    assertEquals(resultProcess.getContact().get(0).getResponsibleParty().getOrganizationName(), component.getContact().get(0).getResponsibleParty().getOrganizationName());
    assertEquals(resultProcess.getContact().get(0).getResponsibleParty(), component.getContact().get(0).getResponsibleParty());
    assertEquals(resultProcess.getContact().get(0), component.getContact().get(0));
    assertEquals(resultProcess.getContact(), component.getContact());
    assertTrue(resultProcess.getClassification().size() == 1);
    assertTrue(resultProcess.getClassification().get(0).getClassifierList().getClassifier().size() == 2);
    assertEquals(resultProcess.getClassification().get(0).getClassifierList().getClassifier().get(0).getTerm(), component.getClassification().get(0).getClassifierList().getClassifier().get(0).getTerm());
    assertEquals(resultProcess.getClassification().get(0).getClassifierList().getClassifier().get(0), component.getClassification().get(0).getClassifierList().getClassifier().get(0));
    assertEquals(resultProcess.getClassification().get(0).getClassifierList().getClassifier(), component.getClassification().get(0).getClassifierList().getClassifier());
    assertEquals(resultProcess.getClassification().get(0).getClassifierList(), component.getClassification().get(0).getClassifierList());
    assertEquals(resultProcess.getClassification().get(0), component.getClassification().get(0));
    assertEquals(resultProcess.getClassification(), component.getClassification());
    assertEquals(resultProcess.getIdentification(), component.getIdentification());
    assertEquals(resultProcess.getValidTime(), component.getValidTime());
    assertEquals(resultProcess.getParameters(), component.getParameters());
    assertEquals(resultProcess.getInputs().getInputList().getInput(), component.getInputs().getInputList().getInput());
    assertEquals(resultProcess.getInputs().getInputList(), component.getInputs().getInputList());
    assertEquals(resultProcess.getInputs(), component.getInputs());
    assertEquals(resultProcess.getOutputs(), component.getOutputs());
    assertEquals(resultProcess.getSMLLocation(), component.getSMLLocation());
    assertEquals(resultProcess.getPosition(), component.getPosition());
    assertEquals(resultProcess.getSpatialReferenceFrame(), component.getSpatialReferenceFrame());
    assertEquals(resultProcess.getDocumentation(), component.getDocumentation());
    assertEquals(resultProcess.getCharacteristics(), component.getCharacteristics());
    assertEquals(resultProcess.getKeywords(), component.getKeywords());
    assertEquals(resultProcess.getParameters(), component.getParameters());
    assertEquals(resultProcess.getName(), component.getName());
    assertEquals(resultProcess, component);
    assertEquals(expectedResult.getMember().get(0), result.getMember().get(0));
    assertEquals(expectedResult.getMember(), result.getMember());
    assertEquals(expectedResult, result);
    SensorMLMarshallerPool.getInstance().recycle(unmarshaller);
}
Also used : DataRecordType(org.geotoolkit.swe.xml.v100.DataRecordType) AbstractDataRecordType(org.geotoolkit.swe.xml.v100.AbstractDataRecordType) Keywords(org.geotoolkit.sml.xml.v100.Keywords) InputList(org.geotoolkit.sml.xml.v100.InputList) ArrayList(java.util.ArrayList) Identification(org.geotoolkit.sml.xml.v100.Identification) Classifier(org.geotoolkit.sml.xml.v100.Classifier) IdentifierList(org.geotoolkit.sml.xml.v100.IdentifierList) ValidTime(org.geotoolkit.sml.xml.v100.ValidTime) UomPropertyType(org.geotoolkit.swe.xml.v100.UomPropertyType) Identifier(org.geotoolkit.sml.xml.v100.Identifier) DefaultIdentifier(org.apache.sis.metadata.iso.DefaultIdentifier) ObservableProperty(org.geotoolkit.swe.xml.v100.ObservableProperty) Classification(org.geotoolkit.sml.xml.v100.Classification) CodeSpacePropertyType(org.geotoolkit.swe.xml.v100.CodeSpacePropertyType) DataComponentPropertyType(org.geotoolkit.swe.xml.v100.DataComponentPropertyType) DefaultIdentifier(org.apache.sis.metadata.iso.DefaultIdentifier) Unmarshaller(javax.xml.bind.Unmarshaller) Member(org.geotoolkit.sml.xml.v100.Member) Inputs(org.geotoolkit.sml.xml.v100.Inputs) TimePositionType(org.geotoolkit.gml.xml.v311.TimePositionType) ComponentType(org.geotoolkit.sml.xml.v100.ComponentType) Parameters(org.geotoolkit.sml.xml.v100.Parameters) Position(org.geotoolkit.sml.xml.v100.Position) InputStream(java.io.InputStream) ClassifierList(org.geotoolkit.sml.xml.v100.ClassifierList) QuantityRange(org.geotoolkit.swe.xml.v100.QuantityRange) JAXBElement(javax.xml.bind.JAXBElement) Term(org.geotoolkit.sml.xml.v100.Term) ResponsibleParty(org.geotoolkit.sml.xml.v100.ResponsibleParty) SensorML(org.geotoolkit.sml.xml.v100.SensorML) IoComponentPropertyType(org.geotoolkit.sml.xml.v100.IoComponentPropertyType) Contact(org.geotoolkit.sml.xml.v100.Contact) TimeRange(org.geotoolkit.swe.xml.v100.TimeRange) TimePeriodType(org.geotoolkit.gml.xml.v311.TimePeriodType) QuantityType(org.geotoolkit.swe.xml.v100.QuantityType) Capabilities(org.geotoolkit.sml.xml.v100.Capabilities) KeywordList(org.geotoolkit.sml.xml.v100.KeywordList) Outputs(org.geotoolkit.sml.xml.v100.Outputs) ParameterList(org.geotoolkit.sml.xml.v100.ParameterList) OutputList(org.geotoolkit.sml.xml.v100.OutputList)

Example 3 with Parameters

use of io.gravitee.am.common.oauth2.Parameters in project gravitee-access-management by gravitee-io.

the class UMATokenGranter method executePolicies.

/**
 * The resource owner works with the authorization server to configure policy conditions (authorization grant rules), which the authorization server executes in the process of issuing access tokens.
 * The authorization process makes use of claims gathered from the requesting party and client in order to satisfy all operative operative policy conditions.
 * @param oAuth2Request OAuth 2.0 Token Request
 * @param client client
 * @param endUser requesting party
 * @return
 */
private Single<OAuth2Request> executePolicies(OAuth2Request oAuth2Request, Client client, User endUser) {
    List<PermissionRequest> permissionRequests = oAuth2Request.getPermissions();
    if (permissionRequests == null || permissionRequests.isEmpty()) {
        return Single.just(oAuth2Request);
    }
    List<String> resourceIds = permissionRequests.stream().map(PermissionRequest::getResourceId).collect(Collectors.toList());
    // find access policies for the given resources
    return resourceService.findAccessPoliciesByResources(resourceIds).map(accessPolicy -> {
        Rule rule = new DefaultRule(accessPolicy);
        Optional<PermissionRequest> permission = permissionRequests.stream().filter(permissionRequest -> permissionRequest.getResourceId().equals(accessPolicy.getResource())).findFirst();
        if (permission.isPresent()) {
            ((DefaultRule) rule).setMetadata(Collections.singletonMap("permissionRequest", permission.get()));
        }
        return rule;
    }).toList().flatMap(rules -> {
        // no policy registered, continue
        if (rules.isEmpty()) {
            return Single.just(oAuth2Request);
        }
        // prepare the execution context
        ExecutionContext simpleExecutionContext = new SimpleExecutionContext(oAuth2Request, oAuth2Request.getHttpResponse());
        ExecutionContext executionContext = executionContextFactory.create(simpleExecutionContext);
        executionContext.setAttribute("client", new ClientProperties(client));
        if (endUser != null) {
            executionContext.setAttribute("user", new UserProperties(endUser));
        }
        // execute the policies
        return rulesEngine.fire(rules, executionContext).toSingleDefault(oAuth2Request).onErrorResumeNext(ex -> Single.error(new InvalidGrantException("Policy conditions are not met for actual request parameters")));
    });
}
Also used : DefaultRule(io.gravitee.am.gateway.handler.uma.policy.DefaultRule) PermissionTicket(io.gravitee.am.model.uma.PermissionTicket) ResourceService(io.gravitee.am.service.ResourceService) java.util(java.util) Client(io.gravitee.am.model.oidc.Client) MultiValueMap(io.gravitee.common.util.MultiValueMap) Maybe(io.reactivex.Maybe) InvalidTokenException(io.gravitee.am.common.exception.oauth2.InvalidTokenException) TokenService(io.gravitee.am.gateway.handler.oauth2.service.token.TokenService) TechnicalException(io.gravitee.am.repository.exceptions.TechnicalException) InvalidScopeException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidScopeException) Single(io.reactivex.Single) JWTService(io.gravitee.am.gateway.handler.common.jwt.JWTService) RulesEngine(io.gravitee.am.gateway.handler.uma.policy.RulesEngine) JsonObject(io.vertx.core.json.JsonObject) Rule(io.gravitee.am.gateway.handler.uma.policy.Rule) PermissionTicketService(io.gravitee.am.service.PermissionTicketService) TokenType(io.gravitee.am.common.oauth2.TokenType) User(io.gravitee.am.model.User) ExecutionContextFactory(io.gravitee.am.gateway.handler.context.ExecutionContextFactory) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) GrantType(io.gravitee.am.common.oauth2.GrantType) ClientProperties(io.gravitee.am.model.safe.ClientProperties) PermissionRequest(io.gravitee.am.model.uma.PermissionRequest) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) JWT(io.gravitee.am.common.jwt.JWT) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) TokenRequest(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest) UmaException(io.gravitee.am.common.exception.uma.UmaException) Domain(io.gravitee.am.model.Domain) AbstractTokenGranter(io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter) Resource(io.gravitee.am.model.uma.Resource) UserInvalidException(io.gravitee.am.service.exception.UserInvalidException) Collectors(java.util.stream.Collectors) Stream(java.util.stream.Stream) RequiredClaims(io.gravitee.am.common.exception.uma.RequiredClaims) Token(io.gravitee.am.gateway.handler.oauth2.service.token.Token) DefaultRule(io.gravitee.am.gateway.handler.uma.policy.DefaultRule) ApplicationScopeSettings(io.gravitee.am.model.application.ApplicationScopeSettings) UserProperties(io.gravitee.am.model.safe.UserProperties) OAuth2Request(io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request) SimpleExecutionContext(io.gravitee.gateway.api.context.SimpleExecutionContext) Parameters(io.gravitee.am.common.oauth2.Parameters) StringUtils(org.springframework.util.StringUtils) PermissionRequest(io.gravitee.am.model.uma.PermissionRequest) ClientProperties(io.gravitee.am.model.safe.ClientProperties) SimpleExecutionContext(io.gravitee.gateway.api.context.SimpleExecutionContext) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) SimpleExecutionContext(io.gravitee.gateway.api.context.SimpleExecutionContext) UserProperties(io.gravitee.am.model.safe.UserProperties) Rule(io.gravitee.am.gateway.handler.uma.policy.Rule) DefaultRule(io.gravitee.am.gateway.handler.uma.policy.DefaultRule)

Example 4 with Parameters

use of io.gravitee.am.common.oauth2.Parameters in project gravitee-access-management by gravitee-io.

the class AuthorizationCodeTokenGranter method parseRequest.

@Override
protected Single<TokenRequest> parseRequest(TokenRequest tokenRequest, Client client) {
    MultiValueMap<String, String> parameters = tokenRequest.parameters();
    String code = parameters.getFirst(Parameters.CODE);
    if (code == null || code.isEmpty()) {
        return Single.error(new InvalidRequestException("Missing parameter: code"));
    }
    return super.parseRequest(tokenRequest, client).flatMap(tokenRequest1 -> authorizationCodeService.remove(code, client).flatMap(authorizationCode -> authenticationFlowContextService.removeContext(authorizationCode.getTransactionId(), authorizationCode.getContextVersion()).onErrorResumeNext(error -> (exitOnError) ? Maybe.error(error) : Maybe.just(new AuthenticationFlowContext())).map(ctx -> {
        checkRedirectUris(tokenRequest1, authorizationCode);
        checkPKCE(tokenRequest1, authorizationCode);
        // set resource owner
        tokenRequest1.setSubject(authorizationCode.getSubject());
        // set original scopes
        tokenRequest1.setScopes(authorizationCode.getScopes());
        // set authorization code initial request parameters (step1 of authorization code flow)
        if (authorizationCode.getRequestParameters() != null) {
            authorizationCode.getRequestParameters().forEach((key, value) -> tokenRequest1.parameters().putIfAbsent(key, value));
        }
        // set decoded authorization code to the current request
        Map<String, Object> decodedAuthorizationCode = new HashMap<>();
        decodedAuthorizationCode.put("code", authorizationCode.getCode());
        decodedAuthorizationCode.put("transactionId", authorizationCode.getTransactionId());
        tokenRequest1.setAuthorizationCode(decodedAuthorizationCode);
        // store only the AuthenticationFlowContext.data attributes in order to simplify EL templating
        // and provide an up to date set of data if the enrichAuthFlow Policy ius used multiple time in a step
        // {#context.attributes['authFlow']['entry']}
        tokenRequest1.getContext().put(ConstantKeys.AUTH_FLOW_CONTEXT_ATTRIBUTES_KEY, ctx.getData());
        return tokenRequest1;
    })).toSingle());
}
Also used : CodeChallengeMethod(io.gravitee.am.common.oauth2.CodeChallengeMethod) Client(io.gravitee.am.model.oidc.Client) MultiValueMap(io.gravitee.common.util.MultiValueMap) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) HashMap(java.util.HashMap) TokenService(io.gravitee.am.gateway.handler.oauth2.service.token.TokenService) Single(io.reactivex.Single) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) TokenRequestResolver(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequestResolver) Map(java.util.Map) User(io.gravitee.am.model.User) PKCEUtils(io.gravitee.am.gateway.handler.oauth2.service.pkce.PKCEUtils) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) AuthenticationFlowContextService(io.gravitee.am.service.AuthenticationFlowContextService) GrantType(io.gravitee.am.common.oauth2.GrantType) Logger(org.slf4j.Logger) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) TokenRequest(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest) AbstractTokenGranter(io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter) AuthorizationCodeService(io.gravitee.am.gateway.handler.oauth2.service.code.AuthorizationCodeService) AuthorizationCode(io.gravitee.am.repository.oauth2.model.AuthorizationCode) Environment(org.springframework.core.env.Environment) AuthenticationFlowContext(io.gravitee.am.model.AuthenticationFlowContext) Parameters(io.gravitee.am.common.oauth2.Parameters) AuthenticationFlowContext(io.gravitee.am.model.AuthenticationFlowContext) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) MultiValueMap(io.gravitee.common.util.MultiValueMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with Parameters

use of io.gravitee.am.common.oauth2.Parameters in project gravitee-access-management by gravitee-io.

the class AuthorizationRequestFailureHandler method processOAuth2Exception.

private void processOAuth2Exception(AuthorizationRequest authorizationRequest, OAuth2Exception oAuth2Exception, Client client, String defaultErrorURL, RoutingContext context, Handler<AsyncResult<String>> handler) {
    final String clientId = authorizationRequest.getClientId();
    // no client available or missing redirect_uri, go to default error page
    if (clientId == null || client == null || authorizationRequest.getRedirectUri() == null) {
        authorizationRequest.setRedirectUri(defaultErrorURL);
    }
    // user set a wrong redirect_uri, go to default error page
    if (oAuth2Exception instanceof RedirectMismatchException) {
        authorizationRequest.setRedirectUri(defaultErrorURL);
    }
    // check if the redirect_uri request parameter is allowed
    if (client != null && client.getRedirectUris() != null && authorizationRequest.getRedirectUri() != null && !client.getRedirectUris().contains(authorizationRequest.getRedirectUri())) {
        authorizationRequest.setRedirectUri(defaultErrorURL);
    }
    // return to the default error page to avoid redirect using wrong response mode
    if (oAuth2Exception instanceof InvalidRequestObjectException && context.get(ConstantKeys.REQUEST_OBJECT_KEY) == null) {
        authorizationRequest.setRedirectUri(defaultErrorURL);
    }
    // Process error response
    try {
        // Response Mode is not supplied by the client, process the response as usual
        if (client == null || authorizationRequest.getResponseMode() == null || !authorizationRequest.getResponseMode().endsWith("jwt")) {
            // redirect user
            handler.handle(Future.succeededFuture(buildRedirectUri(oAuth2Exception.getOAuth2ErrorCode(), oAuth2Exception.getMessage(), authorizationRequest, context)));
            return;
        }
        // Otherwise the JWT contains the error response parameters
        JWTOAuth2Exception jwtException = new JWTOAuth2Exception(oAuth2Exception, authorizationRequest.getState());
        jwtException.setIss(openIDDiscoveryService.getIssuer(authorizationRequest.getOrigin()));
        jwtException.setAud(client.getClientId());
        // There is nothing about expiration. We admit to use the one settled for authorization code validity
        jwtException.setExp(Instant.now().plusSeconds(this.codeValidityInSec).getEpochSecond());
        // Sign if needed, else return unsigned JWT
        jwtService.encodeAuthorization(jwtException.build(), client).flatMap(authorization -> jweService.encryptAuthorization(authorization, client)).subscribe(jwt -> handler.handle(Future.succeededFuture(jwtException.buildRedirectUri(authorizationRequest.getRedirectUri(), authorizationRequest.getResponseType(), authorizationRequest.getResponseMode(), jwt))), ex -> handler.handle(Future.failedFuture(ex)));
    } catch (Exception e) {
        handler.handle(Future.failedFuture(e));
    }
}
Also used : Json(io.vertx.core.json.Json) HttpHeaders(io.gravitee.common.http.HttpHeaders) RedirectMismatchException(io.gravitee.am.gateway.handler.oauth2.exception.RedirectMismatchException) Client(io.gravitee.am.model.oidc.Client) ResponseTypeUtils.isImplicitFlow(io.gravitee.am.service.utils.ResponseTypeUtils.isImplicitFlow) AuthorizationRequestFactory(io.gravitee.am.gateway.handler.oauth2.resources.request.AuthorizationRequestFactory) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) PolicyChainException(io.gravitee.am.gateway.policy.PolicyChainException) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) LinkedHashMap(java.util.LinkedHashMap) OAuth2Exception(io.gravitee.am.common.exception.oauth2.OAuth2Exception) JWTService(io.gravitee.am.gateway.handler.common.jwt.JWTService) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) URI(java.net.URI) HttpException(io.vertx.ext.web.handler.HttpException) ResponseTypeUtils.isHybridFlow(io.gravitee.am.service.utils.ResponseTypeUtils.isHybridFlow) UriBuilder(io.gravitee.am.common.web.UriBuilder) Logger(org.slf4j.Logger) JWEService(io.gravitee.am.gateway.handler.oidc.service.jwe.JWEService) InvalidRequestObjectException(io.gravitee.am.common.exception.oauth2.InvalidRequestObjectException) AuthorizationRequest(io.gravitee.am.gateway.handler.oauth2.service.request.AuthorizationRequest) Instant(java.time.Instant) Future(io.vertx.core.Future) RoutingContext(io.vertx.reactivex.ext.web.RoutingContext) UriBuilderRequest(io.gravitee.am.gateway.handler.common.vertx.utils.UriBuilderRequest) OAuth2ErrorResponse(io.gravitee.am.gateway.handler.oauth2.service.response.OAuth2ErrorResponse) MediaType(io.gravitee.common.http.MediaType) Environment(org.springframework.core.env.Environment) JWTOAuth2Exception(io.gravitee.am.gateway.handler.oauth2.exception.JWTOAuth2Exception) CONTEXT_PATH(io.gravitee.am.gateway.handler.common.vertx.utils.UriBuilderRequest.CONTEXT_PATH) Handler(io.vertx.core.Handler) Parameters(io.gravitee.am.common.oauth2.Parameters) OpenIDDiscoveryService(io.gravitee.am.gateway.handler.oidc.service.discovery.OpenIDDiscoveryService) JWTOAuth2Exception(io.gravitee.am.gateway.handler.oauth2.exception.JWTOAuth2Exception) RedirectMismatchException(io.gravitee.am.gateway.handler.oauth2.exception.RedirectMismatchException) InvalidRequestObjectException(io.gravitee.am.common.exception.oauth2.InvalidRequestObjectException) RedirectMismatchException(io.gravitee.am.gateway.handler.oauth2.exception.RedirectMismatchException) URISyntaxException(java.net.URISyntaxException) PolicyChainException(io.gravitee.am.gateway.policy.PolicyChainException) OAuth2Exception(io.gravitee.am.common.exception.oauth2.OAuth2Exception) HttpException(io.vertx.ext.web.handler.HttpException) InvalidRequestObjectException(io.gravitee.am.common.exception.oauth2.InvalidRequestObjectException) JWTOAuth2Exception(io.gravitee.am.gateway.handler.oauth2.exception.JWTOAuth2Exception)

Aggregations

Client (io.gravitee.am.model.oidc.Client)4 GrantType (io.gravitee.am.common.oauth2.GrantType)3 Parameters (io.gravitee.am.common.oauth2.Parameters)3 ConstantKeys (io.gravitee.am.common.utils.ConstantKeys)3 UserAuthenticationManager (io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager)3 InvalidGrantException (io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException)3 AbstractTokenGranter (io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter)3 TokenRequest (io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest)3 TokenService (io.gravitee.am.gateway.handler.oauth2.service.token.TokenService)3 User (io.gravitee.am.model.User)3 MultiValueMap (io.gravitee.common.util.MultiValueMap)3 Maybe (io.reactivex.Maybe)3 Single (io.reactivex.Single)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 JWTService (io.gravitee.am.gateway.handler.common.jwt.JWTService)2 Map (java.util.Map)2 CodeType (org.geotoolkit.gml.xml.v311.CodeType)2 Address (org.geotoolkit.sml.xml.v101.Address)2 Classification (org.geotoolkit.sml.xml.v101.Classification)2