Search in sources :

Example 11 with OAuth2Request

use of io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request in project gravitee-access-management by gravitee-io.

the class UmaTokenGranterTest method grant_client_extendRptCase.

@Test
public void grant_client_extendRptCase() {
    parameters.remove(CLAIM_TOKEN);
    parameters.remove(CLAIM_TOKEN_FORMAT);
    parameters.add(RPT, RPT_OLD_TOKEN);
    tokenRequest.setScopes(new HashSet<>(Arrays.asList("scopeD")));
    // Set RPT as Client bearer.
    when(rpt.getSub()).thenReturn(CLIENT_ID);
    TestObserver<Token> testObserver = umaTokenGranter.grant(tokenRequest, client).test();
    testObserver.assertComplete().assertNoErrors().assertValue(token -> "success".equals(token.getValue()) && token.isUpgraded());
    OAuth2Request result = oauth2RequestCaptor.getValue();
    assertNull(result.getSubject());
    assertTrue(assertExtendedRptPermissions(result.getPermissions()));
    assertFalse(result.isSupportRefreshToken());
}
Also used : OAuth2Request(io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request) Token(io.gravitee.am.gateway.handler.oauth2.service.token.Token) AccessToken(io.gravitee.am.gateway.handler.oauth2.service.token.impl.AccessToken) Test(org.junit.Test)

Example 12 with OAuth2Request

use of io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request in project gravitee-access-management by gravitee-io.

the class HybridFlow method prepareResponse.

@Override
protected Single<AuthorizationResponse> prepareResponse(AuthorizationRequest authorizationRequest, Client client, User endUser) {
    // Authorization Code is always returned when using the Hybrid Flow.
    return authorizationCodeService.create(authorizationRequest, endUser).flatMap(code -> {
        // prepare response
        HybridResponse hybridResponse = new HybridResponse();
        hybridResponse.setRedirectUri(authorizationRequest.getRedirectUri());
        hybridResponse.setState(authorizationRequest.getState());
        hybridResponse.setCode(code.getCode());
        OAuth2Request oAuth2Request = authorizationRequest.createOAuth2Request();
        oAuth2Request.setGrantType(GrantType.HYBRID);
        oAuth2Request.setSubject(endUser.getId());
        oAuth2Request.getContext().put(Claims.c_hash, code.getCode());
        oAuth2Request.getContext().put(Claims.s_hash, authorizationRequest.getState());
        switch(authorizationRequest.getResponseType()) {
            // code id_token response type MUST include both an Authorization Code and an id_token
            case ResponseType.CODE_ID_TOKEN:
                return idTokenService.create(oAuth2Request, client, endUser).map(idToken -> {
                    hybridResponse.setIdToken(idToken);
                    return hybridResponse;
                });
            // others Hybrid Flow response type MUST include at least an Access Token, an Access Token Type and optionally an ID Token
            default:
                return tokenService.create(oAuth2Request, client, endUser).map(accessToken -> {
                    hybridResponse.setAccessToken(accessToken);
                    return hybridResponse;
                });
        }
    });
}
Also used : OAuth2Request(io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request) HybridResponse(io.gravitee.am.gateway.handler.oauth2.service.response.HybridResponse)

Example 13 with OAuth2Request

use of io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request 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 14 with OAuth2Request

use of io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request in project gravitee-access-management by gravitee-io.

the class TokenServiceImpl method create.

@Override
public Single<Token> create(OAuth2Request oAuth2Request, Client client, User endUser) {
    // create execution context
    return Single.fromCallable(() -> createExecutionContext(oAuth2Request, client, endUser)).flatMap(executionContext -> {
        // create JWT access token
        JWT accessToken = createAccessTokenJWT(oAuth2Request, client, endUser, executionContext);
        // create JWT refresh token
        JWT refreshToken = oAuth2Request.isSupportRefreshToken() ? createRefreshTokenJWT(oAuth2Request, client, endUser, accessToken) : null;
        // and create token response (+ enhance information)
        return Single.zip(jwtService.encode(accessToken, client), (refreshToken != null ? jwtService.encode(refreshToken, client).map(Optional::of) : Single.just(Optional.<String>empty())), (encodedAccessToken, optionalEncodedRefreshToken) -> convert(accessToken, encodedAccessToken, optionalEncodedRefreshToken.orElse(null), oAuth2Request)).flatMap(accessToken1 -> tokenEnhancer.enhance(accessToken1, oAuth2Request, client, endUser, executionContext)).doOnSuccess(token -> storeTokens(accessToken, refreshToken, oAuth2Request));
    });
}
Also used : TokenTypeHint(io.gravitee.am.common.oauth2.TokenTypeHint) AccessTokenRepository(io.gravitee.am.repository.oauth2.api.AccessTokenRepository) java.util(java.util) Client(io.gravitee.am.model.oidc.Client) Completable(io.reactivex.Completable) SecureRandomString(io.gravitee.am.common.utils.SecureRandomString) TokenManager(io.gravitee.am.gateway.handler.oauth2.service.token.TokenManager) MultiValueMap(io.gravitee.common.util.MultiValueMap) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) InvalidTokenException(io.gravitee.am.common.exception.oauth2.InvalidTokenException) TokenService(io.gravitee.am.gateway.handler.oauth2.service.token.TokenService) RefreshTokenRepository(io.gravitee.am.repository.oauth2.api.RefreshTokenRepository) Single(io.reactivex.Single) TokenEnhancer(io.gravitee.am.gateway.handler.oauth2.service.token.TokenEnhancer) JWTException(io.gravitee.am.common.exception.jwt.JWTException) IntrospectionTokenService(io.gravitee.am.gateway.handler.common.oauth2.IntrospectionTokenService) JWTService(io.gravitee.am.gateway.handler.common.jwt.JWTService) User(io.gravitee.am.model.User) ExecutionContextFactory(io.gravitee.am.gateway.handler.context.ExecutionContextFactory) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) TokenClaim(io.gravitee.am.model.TokenClaim) ClientProperties(io.gravitee.am.model.safe.ClientProperties) PermissionRequest(io.gravitee.am.model.uma.PermissionRequest) Logger(org.slf4j.Logger) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) JWT(io.gravitee.am.common.jwt.JWT) TokenRequest(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest) Instant(java.time.Instant) RandomString(io.gravitee.am.common.utils.RandomString) Maps(io.gravitee.common.util.Maps) Token(io.gravitee.am.gateway.handler.oauth2.service.token.Token) Parameters(io.gravitee.am.common.oidc.Parameters) Claims(io.gravitee.am.common.jwt.Claims) UserProperties(io.gravitee.am.model.safe.UserProperties) OAuth2Request(io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request) SimpleExecutionContext(io.gravitee.gateway.api.context.SimpleExecutionContext) OpenIDDiscoveryService(io.gravitee.am.gateway.handler.oidc.service.discovery.OpenIDDiscoveryService) JWT(io.gravitee.am.common.jwt.JWT) SecureRandomString(io.gravitee.am.common.utils.SecureRandomString) RandomString(io.gravitee.am.common.utils.RandomString)

Example 15 with OAuth2Request

use of io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request in project gravitee-access-management by gravitee-io.

the class TokenEnhancerTest method shouldEnhanceToken_withIDToken.

@Test
public void shouldEnhanceToken_withIDToken() {
    OAuth2Request oAuth2Request = new OAuth2Request();
    oAuth2Request.setClientId("client-id");
    oAuth2Request.setScopes(Collections.singleton("openid"));
    Client client = new Client();
    Token accessToken = new AccessToken("token-id");
    String idTokenPayload = "payload";
    when(idTokenService.create(oAuth2Request, client, null, null)).thenReturn(Single.just(idTokenPayload));
    TestObserver<Token> testObserver = tokenEnhancer.enhance(accessToken, oAuth2Request, client, null, null).test();
    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(accessToken1 -> accessToken1.getAdditionalInformation().containsKey("id_token"));
    verify(idTokenService, times(1)).create(any(), any(), any(), any());
}
Also used : OAuth2Request(io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request) AccessToken(io.gravitee.am.gateway.handler.oauth2.service.token.impl.AccessToken) AccessToken(io.gravitee.am.gateway.handler.oauth2.service.token.impl.AccessToken) Client(io.gravitee.am.model.oidc.Client) Test(org.junit.Test)

Aggregations

OAuth2Request (io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request)32 Test (org.junit.Test)27 Client (io.gravitee.am.model.oidc.Client)21 ExecutionContext (io.gravitee.gateway.api.ExecutionContext)17 AccessToken (io.gravitee.am.gateway.handler.oauth2.service.token.impl.AccessToken)15 CertificateProvider (io.gravitee.am.certificate.api.CertificateProvider)12 JWT (io.gravitee.am.common.jwt.JWT)12 Token (io.gravitee.am.gateway.handler.oauth2.service.token.Token)12 User (io.gravitee.am.model.User)10 LinkedMultiValueMap (io.gravitee.common.util.LinkedMultiValueMap)5 ReactableExecutionContext (io.gravitee.am.gateway.handler.context.ReactableExecutionContext)3 IDTokenServiceImpl (io.gravitee.am.gateway.handler.oidc.service.idtoken.impl.IDTokenServiceImpl)3 TokenClaim (io.gravitee.am.model.TokenClaim)3 PermissionRequest (io.gravitee.am.model.uma.PermissionRequest)3 RefreshToken (io.gravitee.am.repository.oauth2.model.RefreshToken)3 InvalidTokenException (io.gravitee.am.common.exception.oauth2.InvalidTokenException)2 JWTService (io.gravitee.am.gateway.handler.common.jwt.JWTService)2 ExecutionContextFactory (io.gravitee.am.gateway.handler.context.ExecutionContextFactory)2 InvalidGrantException (io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException)2 TokenRequest (io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest)2