Search in sources :

Example 16 with Token

use of com.auth0.json.mgmt.Token in project sda-dropwizard-commons by SDA-SE.

the class AuthRSA256ServiceTest method validTokenWithIssuerAndConfiguredRequiredIssuer.

@Test
void validTokenWithIssuerAndConfiguredRequiredIssuer() {
    final Pair<RSAPrivateKey, RSAPublicKey> keyPair = createKeyPair(RSA_PRIVATE_KEY);
    String token = createToken(keyPair, ISSUER, null, 0, 30);
    keyLoader.addKeySource(new JwksTestKeySource(ISSUER, keyPair.getRight(), ISSUER, null));
    final Map<String, Claim> claims = this.service.auth(token);
    assertThat(claims.get(CLAIM_ISSUER).asString()).isEqualTo(ISSUER);
    assertThat(claims.get(CLAIM_NOT_BEFORE).asLong() * 1000L).isLessThan(new Date().getTime());
    assertThat(claims.get(CLAIM_EXPIRE).asLong() * 1000L).isGreaterThan(new Date().getTime());
}
Also used : JwksTestKeySource(org.sdase.commons.server.auth.service.testsources.JwksTestKeySource) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Claim(com.auth0.jwt.interfaces.Claim) Date(java.util.Date) Test(org.junit.jupiter.api.Test)

Example 17 with Token

use of com.auth0.json.mgmt.Token in project sda-dropwizard-commons by SDA-SE.

the class AuthRSA256ServiceTest method validTokenWithKeyIdAndIssuerAndNoConfiguredRequiredIssuer.

@Test
void validTokenWithKeyIdAndIssuerAndNoConfiguredRequiredIssuer() {
    final Pair<RSAPrivateKey, RSAPublicKey> keyPair = createKeyPair(RSA_PRIVATE_KEY);
    String token = createToken(keyPair, ISSUER, KEY_ID, 0, 30);
    keyLoader.addKeySource(new JwksTestKeySource(ISSUER, keyPair.getRight(), null, KEY_ID));
    final Map<String, Claim> claims = this.service.auth(token);
    assertThat(claims.get(CLAIM_ISSUER).asString()).isEqualTo(ISSUER);
    assertThat(claims.get(CLAIM_NOT_BEFORE).asLong() * 1000L).isLessThan(new Date().getTime());
    assertThat(claims.get(CLAIM_EXPIRE).asLong() * 1000L).isGreaterThan(new Date().getTime());
}
Also used : JwksTestKeySource(org.sdase.commons.server.auth.service.testsources.JwksTestKeySource) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Claim(com.auth0.jwt.interfaces.Claim) Date(java.util.Date) Test(org.junit.jupiter.api.Test)

Example 18 with Token

use of com.auth0.json.mgmt.Token in project gravitee-api-management 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)

Example 19 with Token

use of com.auth0.json.mgmt.Token in project gravitee-api-management by gravitee-io.

the class CurrentUserResource method login.

@POST
@Path("/login")
@ApiOperation(value = "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 Map<String, Object> claims = new HashMap<>();
        claims.put(Claims.ISSUER, environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER));
        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> roles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getUsername());
        if (!roles.isEmpty()) {
            roles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
        }
        this.environmentService.findByOrganization(GraviteeContext.getCurrentOrganization()).stream().flatMap(env -> membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, env.getId(), MembershipMemberType.USER, userDetails.getUsername()).stream()).filter(Objects::nonNull).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(userDetails.getUsername()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, userDetails.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
        final TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setType(BEARER);
        tokenEntity.setToken(token);
        final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
        servletResponse.addCookie(bearerCookie);
        return ok(tokenEntity).build();
    }
    return ok().build();
}
Also used : PagedResult(io.gravitee.rest.api.management.rest.model.PagedResult) BEARER(io.gravitee.rest.api.management.rest.model.TokenType.BEARER) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) Duration(java.time.Duration) Response.status(javax.ws.rs.core.Response.status) AbstractResource(io.gravitee.rest.api.management.rest.resource.AbstractResource) URI(java.net.URI) UserDetailRole(io.gravitee.rest.api.idp.api.authentication.UserDetailRole) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Context(javax.ws.rs.core.Context) GroupRepository(io.gravitee.repository.management.api.GroupRepository) Instant(java.time.Instant) NotNull(javax.validation.constraints.NotNull) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) GrantedAuthority(org.springframework.security.core.GrantedAuthority) MediaType(io.gravitee.common.http.MediaType) InvalidImageException(io.gravitee.rest.api.exception.InvalidImageException) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) Response.ok(javax.ws.rs.core.Response.ok) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Request(javax.ws.rs.core.Request) Authentication(org.springframework.security.core.Authentication) JWT(com.auth0.jwt.JWT) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) ApiResponses(io.swagger.annotations.ApiResponses) Inject(javax.inject.Inject) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) io.gravitee.rest.api.model(io.gravitee.rest.api.model) TokensResource(io.gravitee.rest.api.management.rest.resource.TokensResource) Api(io.swagger.annotations.Api) Cookie(javax.servlet.http.Cookie) Logger(org.slf4j.Logger) ImageUtils(io.gravitee.rest.api.security.utils.ImageUtils) HttpServletResponse(javax.servlet.http.HttpServletResponse) Group(io.gravitee.repository.management.model.Group) EntityTag(javax.ws.rs.core.EntityTag) Maps(io.gravitee.common.util.Maps) TimeUnit(java.util.concurrent.TimeUnit) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) TokenAuthenticationFilter(io.gravitee.rest.api.security.filter.TokenAuthenticationFilter) ApiResponse(io.swagger.annotations.ApiResponse) ResourceContext(javax.ws.rs.container.ResourceContext) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Algorithm(com.auth0.jwt.algorithms.Algorithm) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) ApiOperation(io.swagger.annotations.ApiOperation)

Example 20 with Token

use of com.auth0.json.mgmt.Token in project gravitee-api-management by gravitee-io.

the class UserServiceImpl method finalizeResetPassword.

@Override
public UserEntity finalizeResetPassword(ResetPasswordUserEntity registerUserEntity) {
    try {
        DecodedJWT jwt = getDecodedJWT(registerUserEntity.getToken());
        final String action = jwt.getClaim(Claims.ACTION).asString();
        if (!RESET_PASSWORD.name().equals(action)) {
            throw new UserStateConflictException("Invalid action on reset password resource");
        }
        final Object subject = jwt.getSubject();
        User user;
        if (subject == null) {
            throw new UserNotFoundException("Subject missing from JWT token");
        } else {
            final String username = subject.toString();
            LOGGER.debug("Find user {} to update password", username);
            Optional<User> checkUser = userRepository.findById(username);
            user = checkUser.orElseThrow(() -> new UserNotFoundException(username));
        }
        // Set date fields
        user.setUpdatedAt(new Date());
        // Encrypt password if internal user
        encryptPassword(user, registerUserEntity.getPassword());
        user = userRepository.update(user);
        auditService.createOrganizationAuditLog(GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, user.getId()), User.AuditEvent.PASSWORD_CHANGED, user.getUpdatedAt(), null, null);
        // Do not send back the password
        user.setPassword(null);
        return convert(user, true);
    } catch (AbstractManagementException ex) {
        throw ex;
    } catch (Exception ex) {
        LOGGER.error("An error occurs while trying to change password of an internal user with the token {}", registerUserEntity.getToken(), ex);
        throw new TechnicalManagementException(ex.getMessage(), ex);
    }
}
Also used : User(io.gravitee.repository.management.model.User) UuidString(io.gravitee.rest.api.service.common.UuidString) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) TechnicalException(io.gravitee.repository.exceptions.TechnicalException)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)276 Algorithm (com.auth0.jwt.algorithms.Algorithm)147 Test (org.junit.Test)120 JWTVerifier (com.auth0.jwt.JWTVerifier)97 Date (java.util.Date)78 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)62 IOException (java.io.IOException)59 Claim (com.auth0.jwt.interfaces.Claim)49 HashMap (java.util.HashMap)40 VoidRequest (com.auth0.net.VoidRequest)31 RSAPublicKey (java.security.interfaces.RSAPublicKey)31 Test (org.junit.jupiter.api.Test)30 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)28 JWTCreator (com.auth0.jwt.JWTCreator)21 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 JWT (com.auth0.jwt.JWT)20 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 Instant (java.time.Instant)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17