Search in sources :

Example 1 with Token

use of io.gravitee.rest.api.portal.rest.model.Token in project gravitee-management-rest-api by gravitee-io.

the class AuthResourceTest method shouldLogin.

@Test
public void shouldLogin() {
    final UserDetails userDetails = new UserDetails(USER_NAME, "PASSWORD", Collections.emptyList());
    final Authentication authentication = mock(Authentication.class);
    when(authentication.getPrincipal()).thenReturn(userDetails);
    final SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
    SecurityContextHolder.setContext(securityContext);
    Cookie bearer = new Cookie("FOO", "BAR");
    doReturn(bearer).when(cookieGenerator).generate(any());
    final Response response = target().path("login").request().post(null);
    assertEquals(HttpStatusCode.OK_200, response.getStatus());
    Token token = response.readEntity(Token.class);
    assertNotNull(token);
    assertNotNull(token.getToken());
    assertNotEquals("", token.getToken());
    assertEquals(TokenTypeEnum.BEARER, token.getTokenType());
// APIPortal: can't test Cookie, since servletResponse is mocked
}
Also used : Cookie(javax.servlet.http.Cookie) Response(javax.ws.rs.core.Response) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) Token(io.gravitee.rest.api.portal.rest.model.Token) Test(org.junit.Test)

Example 2 with Token

use of io.gravitee.rest.api.portal.rest.model.Token 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 3 with Token

use of io.gravitee.rest.api.portal.rest.model.Token in project gravitee-management-rest-api by gravitee-io.

the class AbstractAuthenticationResource method connectUser.

protected Response connectUser(String userId, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
    UserEntity user = userService.connect(userId);
    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 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()));
    }
    // 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 sign = 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 Token tokenEntity = new Token();
    tokenEntity.setTokenType(TokenTypeEnum.BEARER);
    tokenEntity.setToken(sign);
    if (idToken != null) {
        tokenEntity.setAccessToken(accessToken);
        tokenEntity.setIdToken(idToken);
    }
    if (state != null && !state.isEmpty()) {
        tokenEntity.setState(state);
    }
    final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
    servletResponse.addCookie(bearerCookie);
    return Response.ok(tokenEntity).build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) 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) 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) 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) Response(javax.ws.rs.core.Response) 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) Token(io.gravitee.rest.api.portal.rest.model.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm) UserEntity(io.gravitee.rest.api.model.UserEntity) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication)

Example 4 with Token

use of io.gravitee.rest.api.portal.rest.model.Token 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 {
    Token responseToken = response.readEntity(Token.class);
    assertEquals("BEARER", responseToken.getTokenType().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("Jane", jwt.getClaim("firstname").asString());
    assertEquals("gravitee-management-auth", jwt.getClaim("iss").asString());
    assertEquals("janedoe@example.com", jwt.getClaim("sub").asString());
    assertEquals("janedoe@example.com", jwt.getClaim("email").asString());
    assertEquals("Doe", jwt.getClaim("lastname").asString());
}
Also used : Token(io.gravitee.rest.api.portal.rest.model.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Aggregations

Token (io.gravitee.rest.api.portal.rest.model.Token)4 Algorithm (com.auth0.jwt.algorithms.Algorithm)3 UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)3 Cookie (javax.servlet.http.Cookie)3 Response (javax.ws.rs.core.Response)3 Authentication (org.springframework.security.core.Authentication)3 JWT (com.auth0.jwt.JWT)2 Maps (io.gravitee.common.util.Maps)2 MembershipMemberType (io.gravitee.rest.api.model.MembershipMemberType)2 MembershipReferenceType (io.gravitee.rest.api.model.MembershipReferenceType)2 RoleEntity (io.gravitee.rest.api.model.RoleEntity)2 TokenTypeEnum (io.gravitee.rest.api.portal.rest.model.Token.TokenTypeEnum)2 CookieGenerator (io.gravitee.rest.api.security.cookies.CookieGenerator)2 GraviteeContext (io.gravitee.rest.api.service.common.GraviteeContext)2 DEFAULT_JWT_EXPIRE_AFTER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER)2 DEFAULT_JWT_ISSUER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER)2 Duration (java.time.Duration)2 Instant (java.time.Instant)2 java.util (java.util)2 Collectors (java.util.stream.Collectors)2