use of io.gravitee.management.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class SubscriptionServiceTest method shouldCreateWithAutomaticSubscription_forApiKey.
@Test
public void shouldCreateWithAutomaticSubscription_forApiKey() throws Exception {
// Prepare data
when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
when(plan.getValidation()).thenReturn(PlanValidationType.AUTO);
when(plan.getSecurity()).thenReturn(PlanSecurityType.API_KEY);
// 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);
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("tester", "password", 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) {
}
});
// Stub
when(planService.findById(PLAN_ID)).thenReturn(plan);
when(applicationService.findById(APPLICATION_ID)).thenReturn(application);
when(apiService.findByIdForTemplates(API_ID)).thenReturn(apiModelEntity);
when(subscriptionRepository.update(any())).thenAnswer(returnsFirstArg());
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;
}
});
when(subscriptionRepository.findById(SUBSCRIPTION_ID)).thenAnswer(new Answer<Optional<Subscription>>() {
@Override
public Optional<Subscription> answer(InvocationOnMock invocation) throws Throwable {
subscription.setCreatedAt(new Date());
return Optional.of(subscription);
}
});
// Run
final SubscriptionEntity subscriptionEntity = subscriptionService.create(new NewSubscriptionEntity(PLAN_ID, APPLICATION_ID));
// Verify
verify(subscriptionRepository, times(1)).create(any(Subscription.class));
verify(subscriptionRepository, times(1)).update(any(Subscription.class));
verify(apiKeyService, times(1)).generate(any());
assertNotNull(subscriptionEntity.getId());
assertNotNull(subscriptionEntity.getApplication());
assertNotNull(subscriptionEntity.getCreatedAt());
}
use of io.gravitee.management.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class SubscriptionServiceTest method shouldCreateWithoutProcess.
@Test
public void shouldCreateWithoutProcess() throws Exception {
// Prepare data
when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
when(plan.getValidation()).thenReturn(PlanValidationType.MANUAL);
// Stub
when(planService.findById(PLAN_ID)).thenReturn(plan);
when(applicationService.findById(APPLICATION_ID)).thenReturn(application);
when(apiService.findByIdForTemplates(API_ID)).thenReturn(apiModelEntity);
when(subscriptionRepository.create(any())).thenAnswer(returnsFirstArg());
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("tester", "password", 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) {
}
});
// Run
final SubscriptionEntity subscriptionEntity = subscriptionService.create(new NewSubscriptionEntity(PLAN_ID, APPLICATION_ID));
// Verify
verify(subscriptionRepository, times(1)).create(any(Subscription.class));
verify(subscriptionRepository, never()).update(any(Subscription.class));
verify(apiKeyService, never()).generate(any());
assertNotNull(subscriptionEntity.getId());
assertNotNull(subscriptionEntity.getApplication());
assertNotNull(subscriptionEntity.getCreatedAt());
}
use of io.gravitee.management.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class SubscriptionServiceTest method shouldCreateWithAutomaticSubscription_notApiKey.
@Test
public void shouldCreateWithAutomaticSubscription_notApiKey() throws Exception {
// Prepare data
when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
when(plan.getValidation()).thenReturn(PlanValidationType.AUTO);
when(plan.getSecurity()).thenReturn(PlanSecurityType.OAUTH2);
when(application.getClientId()).thenReturn("my-client-id");
// 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);
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("tester", "password", 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) {
}
});
// Stub
when(planService.findById(PLAN_ID)).thenReturn(plan);
when(applicationService.findById(APPLICATION_ID)).thenReturn(application);
when(apiService.findByIdForTemplates(API_ID)).thenReturn(apiModelEntity);
when(subscriptionRepository.update(any())).thenAnswer(returnsFirstArg());
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;
}
});
when(subscriptionRepository.findById(SUBSCRIPTION_ID)).thenAnswer(new Answer<Optional<Subscription>>() {
@Override
public Optional<Subscription> answer(InvocationOnMock invocation) throws Throwable {
subscription.setCreatedAt(new Date());
return Optional.of(subscription);
}
});
// Run
final SubscriptionEntity subscriptionEntity = subscriptionService.create(new NewSubscriptionEntity(PLAN_ID, APPLICATION_ID));
// Verify
verify(subscriptionRepository, times(1)).create(any(Subscription.class));
verify(subscriptionRepository, times(1)).update(any(Subscription.class));
verify(apiKeyService, never()).generate(any());
assertNotNull(subscriptionEntity.getId());
assertNotNull(subscriptionEntity.getApplication());
assertNotNull(subscriptionEntity.getCreatedAt());
}
use of io.gravitee.management.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class AuthenticationSuccessFilter method doFilter.
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) servletRequest;
final Optional<Cookie> optionalStringToken;
if (req.getCookies() == null) {
optionalStringToken = Optional.empty();
} else {
optionalStringToken = Arrays.stream(req.getCookies()).filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).filter(cookie -> cookie.getValue() != null && !cookie.getValue().isEmpty()).findAny();
}
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !optionalStringToken.isPresent()) {
// JWT signer
final Map<String, Object> claims = new HashMap<>();
claims.put(Claims.ISSUER, jwtIssuer);
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
Set<GrantedAuthority> authorities = new HashSet<>(userDetails.getAuthorities());
// We must also load permissions from repository for configured management or portal role
RoleEntity role = membershipService.getRole(MembershipReferenceType.MANAGEMENT, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.MANAGEMENT);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
role = membershipService.getRole(MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.PORTAL);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
claims.put(Claims.PERMISSIONS, authorities);
claims.put(Claims.SUBJECT, userDetails.getUsername());
claims.put(Claims.EMAIL, userDetails.getEmail());
claims.put(Claims.FIRSTNAME, userDetails.getFirstname());
claims.put(Claims.LASTNAME, userDetails.getLastname());
final JWTSigner.Options options = new JWTSigner.Options();
options.setExpirySeconds(jwtExpireAfter);
options.setIssuedAt(true);
options.setJwtId(true);
final Cookie bearerCookie = jwtCookieGenerator.generate("Bearer " + new JWTSigner(jwtSecret).sign(claims, options));
((HttpServletResponse) servletResponse).addCookie(bearerCookie);
}
filterChain.doFilter(servletRequest, servletResponse);
}
use of io.gravitee.management.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.
the class JWTAuthenticationFilter method doFilter.
@Override
@SuppressWarnings(value = "unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
final Optional<Cookie> optionalStringToken;
if (req.getCookies() == null) {
optionalStringToken = Optional.empty();
} else {
optionalStringToken = Arrays.stream(req.getCookies()).filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).findAny();
}
if (optionalStringToken.isPresent()) {
String stringToken = optionalStringToken.get().getValue();
final String authorizationSchema = "Bearer";
if (stringToken.contains(authorizationSchema)) {
stringToken = stringToken.substring(authorizationSchema.length()).trim();
try {
final Map<String, Object> verify = jwtVerifier.verify(stringToken);
List<Map> permissions = (List<Map>) verify.get(Claims.PERMISSIONS);
List<SimpleGrantedAuthority> authorities;
if (permissions != null) {
authorities = ((List<Map>) verify.get(Claims.PERMISSIONS)).stream().map(map -> new SimpleGrantedAuthority(map.get("authority").toString())).collect(Collectors.toList());
} else {
authorities = Collections.emptyList();
}
final UserDetails userDetails = new UserDetails(getStringValue(verify.get(Claims.SUBJECT)), "", authorities);
userDetails.setEmail((String) verify.get(Claims.EMAIL));
userDetails.setFirstname((String) verify.get(Claims.FIRSTNAME));
userDetails.setLastname((String) verify.get(Claims.LASTNAME));
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()));
} catch (Exception e) {
LOGGER.error("Invalid token", e);
final Cookie bearerCookie = jwtCookieGenerator.generate(null);
res.addCookie(bearerCookie);
res.sendError(HttpStatusCode.UNAUTHORIZED_401);
}
} else {
LOGGER.debug("Authorization schema not found");
}
}
chain.doFilter(request, response);
}
Aggregations