use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api 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();
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class CockpitAuthenticationResource method tokenExchange.
@GET
public Response tokenExchange(@QueryParam(value = "token") final String token, @Context final HttpServletResponse httpResponse) {
if (!enabled) {
return Response.status(Response.Status.NOT_FOUND).build();
}
try {
// Verify and get claims from token.
final JWTClaimsSet jwtClaimsSet = jwtProcessor.process(token, null);
// Current organization must be set to those coming from cockpit token.
final String organizationId = jwtClaimsSet.getStringClaim(ORG_CLAIM);
GraviteeContext.setCurrentOrganization(organizationId);
// Retrieve the user.
final UserEntity user = userService.findBySource(COCKPIT_SOURCE, jwtClaimsSet.getSubject(), true);
// set user to Authentication Context
final String environmentId = jwtClaimsSet.getStringClaim(ENVIRONMENT_CLAIM);
final Set<GrantedAuthority> authorities = authoritiesProvider.retrieveAuthorities(user.getId(), organizationId, environmentId);
UserDetails userDetails = new UserDetails(user.getId(), "", authorities);
userDetails.setEmail(user.getEmail());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, authorities));
// Cockpit user is authenticated, connect user (ie: generate cookie).
super.connectUser(user, httpResponse);
// Redirect the user.
return Response.temporaryRedirect(new URI(jwtClaimsSet.getStringClaim(REDIRECT_URI_CLAIM) + "?organization=" + jwtClaimsSet.getStringClaim(ORG_CLAIM) + "/#!/environments/" + jwtClaimsSet.getStringClaim(ENVIRONMENT_CLAIM))).build();
} catch (Exception e) {
LOGGER.error("Error occurred when trying to log user using cockpit.", e);
return Response.serverError().build();
} finally {
GraviteeContext.cleanContext();
}
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class TokenServiceTest method init.
@Before
public void init() throws TechnicalException {
setField(tokenService, "passwordEncoder", passwordEncoder);
when(passwordEncoder.matches(any(), any())).thenReturn(true);
when(token.getId()).thenReturn(TOKEN_ID);
when(token.getName()).thenReturn("name");
when(token.getToken()).thenReturn("token");
when(token.getCreatedAt()).thenReturn(new Date(1486771200000L));
when(token.getExpiresAt()).thenReturn(new Date(1486772200000L));
when(token.getLastUseAt()).thenReturn(new Date(1486773200000L));
when(tokenRepository.findById(TOKEN_ID)).thenReturn(of(token));
SecurityContextHolder.setContext(new SecurityContext() {
@Override
public Authentication getAuthentication() {
return new Authentication() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return new UserDetails(USER_ID, "", Collections.emptyList());
}
@Override
public boolean isAuthenticated() {
return false;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
@Override
public String getName() {
return null;
}
};
}
@Override
public void setAuthentication(Authentication authentication) {
}
});
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class SubscriptionServiceTest method shouldCreateWithGroupRestriction_BecauseAdmin.
public void shouldCreateWithGroupRestriction_BecauseAdmin() throws Exception {
// Prepare data
when(plan.getExcludedGroups()).thenReturn(asList("excl1", "excl2"));
when(plan.getApi()).thenReturn("api1");
when(planService.findById(PLAN_ID)).thenReturn(plan);
// subscription object is not a mock since its state is updated by the call to subscriptionService.create()
Subscription subscription = new Subscription();
subscription.setId(SUBSCRIPTION_ID);
subscription.setApplication(APPLICATION_ID);
subscription.setPlan(PLAN_ID);
subscription.setStatus(Subscription.Status.PENDING);
subscription.setSubscribedBy(SUBSCRIBER_ID);
final UserEntity subscriberUser = new UserEntity();
subscriberUser.setEmail(SUBSCRIBER_ID + "@acme.net");
when(userService.findById(SUBSCRIBER_ID)).thenReturn(subscriberUser);
// Stub
when(planService.findById(PLAN_ID)).thenReturn(plan);
when(applicationService.findById(APPLICATION_ID)).thenReturn(application);
when(apiService.findByIdForTemplates("api1")).thenReturn(apiModelEntity);
when(subscriptionRepository.create(any())).thenAnswer(new Answer<Subscription>() {
@Override
public Subscription answer(InvocationOnMock invocation) throws Throwable {
Subscription subscription = (Subscription) invocation.getArguments()[0];
subscription.setId(SUBSCRIPTION_ID);
return subscription;
}
});
final SecurityContext securityContext = mock(SecurityContext.class);
UserDetails principal = new UserDetails("toto", "pwdtoto", asList(new SimpleGrantedAuthority(ENVIRONMENT_ADMIN)));
Authentication authMock = new TestingAuthenticationToken(principal, null, ENVIRONMENT_ADMIN);
when(securityContext.getAuthentication()).thenReturn(authMock);
SecurityContextHolder.setContext(securityContext);
// Run
final SubscriptionEntity subscriptionEntity = subscriptionService.create(new NewSubscriptionEntity(PLAN_ID, APPLICATION_ID));
// Verify
verify(subscriptionRepository, times(1)).create(any(Subscription.class));
assertNotNull(subscriptionEntity.getId());
assertNotNull(subscriptionEntity.getApplication());
assertNotNull(subscriptionEntity.getCreatedAt());
}
use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class FilteringServiceTest method shouldGetMineApi.
@Test
public void shouldGetMineApi() {
final Authentication authentication = mock(Authentication.class);
when(authentication.getPrincipal()).thenReturn(new UserDetails("user", "", emptyList()));
final SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
ApplicationListItem appA = new ApplicationListItem();
appA.setId("A");
ApplicationListItem appB = new ApplicationListItem();
appB.setId("B");
ApplicationListItem appC = new ApplicationListItem();
appC.setId("C");
doReturn(new HashSet<ApplicationListItem>(Arrays.asList(appC, appB, appA))).when(applicationService).findByUser(any());
SubscriptionEntity subA1 = new SubscriptionEntity();
subA1.setApplication("A");
subA1.setApi("1");
SubscriptionEntity subA2 = new SubscriptionEntity();
subA2.setApplication("A");
subA2.setApi("2");
SubscriptionEntity subB1 = new SubscriptionEntity();
subB1.setApplication("B");
subB1.setApi("1");
SubscriptionEntity subC4 = new SubscriptionEntity();
subC4.setApplication("C");
subC4.setApi("4");
SubscriptionEntity subC8 = new SubscriptionEntity();
subC8.setApplication("C");
subC8.setApi("8");
doReturn(Arrays.asList(subC8, subA2, subB1, subC4, subA1)).when(subscriptionService).search(any());
FilteredEntities<ApiEntity> apiEntityFilteredEntities = filteringService.filterApis(mockApis, FilteringService.FilterType.MINE, null);
List<ApiEntity> filteredItems = apiEntityFilteredEntities.getFilteredItems();
assertEquals(2, filteredItems.size());
assertEquals("1", filteredItems.get(0).getId());
assertEquals("4", filteredItems.get(1).getId());
}
Aggregations