Search in sources :

Example 66 with JWT

use of com.auth0.jwt.JWT in project spring-boot by spring-projects.

the class ReactiveOAuth2ResourceServerAutoConfigurationTests method autoConfigurationShouldConfigureResourceServerUsingJwkSetUriAndIssuerUri.

@SuppressWarnings("unchecked")
@Test
void autoConfigurationShouldConfigureResourceServerUsingJwkSetUriAndIssuerUri() throws Exception {
    this.server = new MockWebServer();
    this.server.start();
    String path = "test";
    String issuer = this.server.url(path).toString();
    String cleanIssuerPath = cleanIssuerPath(issuer);
    setupMockResponse(cleanIssuerPath);
    this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> {
        assertThat(context).hasSingleBean(ReactiveJwtDecoder.class);
        ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class);
        DelegatingOAuth2TokenValidator<Jwt> jwtValidator = (DelegatingOAuth2TokenValidator<Jwt>) ReflectionTestUtils.getField(reactiveJwtDecoder, "jwtValidator");
        Collection<OAuth2TokenValidator<Jwt>> tokenValidators = (Collection<OAuth2TokenValidator<Jwt>>) ReflectionTestUtils.getField(jwtValidator, "tokenValidators");
        assertThat(tokenValidators).hasAtLeastOneElementOfType(JwtIssuerValidator.class);
    });
}
Also used : NimbusReactiveJwtDecoder(org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) SupplierReactiveJwtDecoder(org.springframework.security.oauth2.jwt.SupplierReactiveJwtDecoder) OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) DelegatingOAuth2TokenValidator(org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator) Jwt(org.springframework.security.oauth2.jwt.Jwt) MockWebServer(okhttp3.mockwebserver.MockWebServer) Collection(java.util.Collection) DelegatingOAuth2TokenValidator(org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator) Test(org.junit.jupiter.api.Test)

Example 67 with JWT

use of com.auth0.jwt.JWT in project dhis2-core by dhis2.

the class Dhis2JwtAuthenticationManagerResolver method getAuthenticationManager.

/**
 * Looks for a DhisOidcClientRegistration in the DhisOidcProviderRepository
 * that matches the input JWT "issuer". It creates a new
 * DhisJwtAuthenticationProvider if it finds a matching config.
 * <p>
 * The DhisJwtAuthenticationProvider is configured with a custom
 * {@link Converter} that "converts" the incoming JWT token into a
 * {@link DhisJwtAuthenticationToken}.
 * <p>
 * It also configures a JWT decoder that "decodes" incoming JSON string into
 * a JWT token ({@link Jwt}
 *
 * @param issuer JWT issuer to look up
 *
 * @return a DhisJwtAuthenticationProvider
 */
private AuthenticationManager getAuthenticationManager(String issuer) {
    return this.authenticationManagers.computeIfAbsent(issuer, s -> {
        DhisOidcClientRegistration clientRegistration = clientRegistrationRepository.findByIssuerUri(issuer);
        if (clientRegistration == null) {
            throw new InvalidBearerTokenException("Invalid issuer");
        }
        Converter<Jwt, DhisJwtAuthenticationToken> authConverter = getConverter(clientRegistration);
        JwtDecoder decoder = getDecoder(issuer);
        return new DhisJwtAuthenticationProvider(decoder, authConverter)::authenticate;
    });
}
Also used : DhisOidcClientRegistration(org.hisp.dhis.security.oidc.DhisOidcClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) InvalidBearerTokenException(org.springframework.security.oauth2.server.resource.InvalidBearerTokenException)

Example 68 with JWT

use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.

the class OAuth2AuthenticationResourceTest method verifyJwtToken.

private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
    TokenEntity responseToken = response.readEntity(TokenEntity.class);
    assertEquals("BEARER", responseToken.getType().name());
    String token = responseToken.getToken();
    Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
    JWTVerifier jwtVerifier = JWT.require(algorithm).build();
    DecodedJWT jwt = jwtVerifier.verify(token);
    assertEquals(jwt.getSubject(), "janedoe@example.com");
    assertEquals(jwt.getClaim("firstname").asString(), "Jane");
    assertEquals(jwt.getClaim("iss").asString(), "gravitee-management-auth");
    assertEquals(jwt.getClaim("sub").asString(), "janedoe@example.com");
    assertEquals(jwt.getClaim("email").asString(), "janedoe@example.com");
    assertEquals(jwt.getClaim("lastname").asString(), "Doe");
}
Also used : TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 69 with JWT

use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.

the class AuthResource method login.

@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public Response login(@Context final javax.ws.rs.core.HttpHeaders headers, @Context final HttpServletResponse servletResponse) {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
        // JWT signer
        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // Manage authorities, initialize it with dynamic permissions from the IDP
        List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
        // We must also load permissions from repository for configured environment role
        Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), MembershipMemberType.USER, userDetails.getId());
        if (!userRoles.isEmpty()) {
            userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
        }
        Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
        Date issueAt = new Date();
        Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
        final String sign = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(userDetails.getUsername()).withClaim(Claims.PERMISSIONS, authorities).withClaim(Claims.EMAIL, userDetails.getEmail()).withClaim(Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
        final Token tokenEntity = new Token();
        tokenEntity.setTokenType(TokenTypeEnum.BEARER);
        tokenEntity.setToken(sign);
        final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
        servletResponse.addCookie(bearerCookie);
        return ok(tokenEntity).build();
    }
    return ok().build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) Duration(java.time.Duration) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuth2AuthenticationResource(io.gravitee.rest.api.portal.rest.resource.auth.OAuth2AuthenticationResource) Token(io.gravitee.rest.api.portal.rest.model.Token) TokenTypeEnum(io.gravitee.rest.api.portal.rest.model.Token.TokenTypeEnum) Instant(java.time.Instant) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) Maps(io.gravitee.common.util.Maps) RoleEntity(io.gravitee.rest.api.model.RoleEntity) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) MediaType(io.gravitee.common.http.MediaType) Response(javax.ws.rs.core.Response) ResourceContext(javax.ws.rs.container.ResourceContext) Response.ok(javax.ws.rs.core.Response.ok) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Token(io.gravitee.rest.api.portal.rest.model.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 70 with JWT

use of com.auth0.jwt.JWT in project gravitee-management-rest-api by gravitee-io.

the class AbstractAuthenticationResource method connectUserInternal.

protected Response connectUserInternal(UserEntity user, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    // Manage authorities, initialize it with dynamic permissions from the IDP
    List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
    // We must also load permissions from repository for configured management or portal role
    Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getId());
    if (!userRoles.isEmpty()) {
        userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
    }
    // JWT signer
    Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
    Date issueAt = new Date();
    Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
    final String token = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
    final TokenEntity tokenEntity = new TokenEntity();
    tokenEntity.setType(BEARER);
    tokenEntity.setToken(token);
    if (idToken != null) {
        tokenEntity.setAccessToken(accessToken);
        tokenEntity.setIdToken(idToken);
    }
    if (state != null && !state.isEmpty()) {
        tokenEntity.setState(state);
    }
    final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
    servletResponse.addCookie(bearerCookie);
    return Response.ok(tokenEntity).build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) NotBlank(javax.validation.constraints.NotBlank) BEARER(io.gravitee.rest.api.management.rest.model.TokenType.BEARER) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) UserService(io.gravitee.rest.api.service.UserService) Duration(java.time.Duration) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) MembershipService(io.gravitee.rest.api.service.MembershipService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Instant(java.time.Instant) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) Maps(io.gravitee.common.util.Maps) RoleEntity(io.gravitee.rest.api.model.RoleEntity) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) Response(javax.ws.rs.core.Response) TokenAuthenticationFilter(io.gravitee.rest.api.security.filter.TokenAuthenticationFilter) Environment(org.springframework.core.env.Environment) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) UserEntity(io.gravitee.rest.api.model.UserEntity) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity)

Aggregations

Jwt (org.springframework.security.oauth2.jwt.Jwt)99 Test (org.junit.jupiter.api.Test)80 GrantedAuthority (org.springframework.security.core.GrantedAuthority)51 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)23 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)19 Arrays (java.util.Arrays)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)18 List (java.util.List)17 Algorithm (com.auth0.jwt.algorithms.Algorithm)16 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)16 Authentication (org.springframework.security.core.Authentication)16 Test (org.junit.Test)14 HashMap (java.util.HashMap)13 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 Instant (java.time.Instant)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 JWTVerifier (com.auth0.jwt.JWTVerifier)10