Search in sources :

Example 16 with UserDetails

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();
}
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 17 with UserDetails

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();
    }
}
Also used : UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) URI(java.net.URI) UserEntity(io.gravitee.rest.api.model.UserEntity) GET(javax.ws.rs.GET)

Example 18 with UserDetails

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) {
        }
    });
}
Also used : UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) Collection(java.util.Collection) Date(java.util.Date) Before(org.junit.Before)

Example 19 with UserDetails

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());
}
Also used : TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) Subscription(io.gravitee.repository.management.model.Subscription)

Example 20 with UserDetails

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());
}
Also used : ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) TopApiEntity(io.gravitee.rest.api.model.TopApiEntity) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) SubscriptionEntity(io.gravitee.rest.api.model.SubscriptionEntity) Test(org.junit.Test)

Aggregations

UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)21 Authentication (org.springframework.security.core.Authentication)11 Response (javax.ws.rs.core.Response)9 Cookie (javax.servlet.http.Cookie)7 GrantedAuthority (org.springframework.security.core.GrantedAuthority)7 JWT (com.auth0.jwt.JWT)6 Algorithm (com.auth0.jwt.algorithms.Algorithm)6 UserEntity (io.gravitee.rest.api.model.UserEntity)6 CookieGenerator (io.gravitee.rest.api.security.cookies.CookieGenerator)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 SecurityContextHolder (org.springframework.security.core.context.SecurityContextHolder)6 Maps (io.gravitee.common.util.Maps)5 GraviteeContext (io.gravitee.rest.api.service.common.GraviteeContext)5 DEFAULT_JWT_EXPIRE_AFTER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER)5 DEFAULT_JWT_ISSUER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER)5 Duration (java.time.Duration)5 Instant (java.time.Instant)5 java.util (java.util)5 Collectors (java.util.stream.Collectors)5 Claims (io.gravitee.rest.api.service.common.JWTHelper.Claims)4