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
}
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();
}
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();
}
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());
}
Aggregations