Search in sources :

Example 1 with UserDetails

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

Example 2 with UserDetails

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());
}
Also used : GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) Subscription(io.gravitee.repository.management.model.Subscription) Test(org.junit.Test)

Example 3 with UserDetails

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

Example 4 with UserDetails

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);
}
Also used : Cookie(javax.servlet.http.Cookie) JWTCookieGenerator(io.gravitee.management.security.cookies.JWTCookieGenerator) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) RoleScope(io.gravitee.repository.management.model.RoleScope) FilterChain(javax.servlet.FilterChain) ServletRequest(javax.servlet.ServletRequest) java.util(java.util) HttpHeaders(io.gravitee.common.http.HttpHeaders) RoleEntity(io.gravitee.management.model.RoleEntity) ServletException(javax.servlet.ServletException) MembershipDefaultReferenceId(io.gravitee.repository.management.model.MembershipDefaultReferenceId) HttpServletResponse(javax.servlet.http.HttpServletResponse) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) IOException(java.io.IOException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletRequest(javax.servlet.http.HttpServletRequest) MembershipService(io.gravitee.management.service.MembershipService) ServletResponse(javax.servlet.ServletResponse) GenericFilterBean(org.springframework.web.filter.GenericFilterBean) JWTSigner(com.auth0.jwt.JWTSigner) Claims(io.gravitee.management.service.common.JWTHelper.Claims) MembershipReferenceType(io.gravitee.repository.management.model.MembershipReferenceType) Authentication(org.springframework.security.core.Authentication) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Cookie(javax.servlet.http.Cookie) JWTSigner(com.auth0.jwt.JWTSigner) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) RoleEntity(io.gravitee.management.model.RoleEntity) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication)

Example 5 with UserDetails

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);
}
Also used : Cookie(javax.servlet.http.Cookie) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails)

Aggregations

UserDetails (io.gravitee.management.idp.api.authentication.UserDetails)13 Authentication (org.springframework.security.core.Authentication)7 GrantedAuthority (org.springframework.security.core.GrantedAuthority)7 UserNotFoundException (io.gravitee.management.service.exceptions.UserNotFoundException)5 SecurityContext (org.springframework.security.core.context.SecurityContext)5 UserEntity (io.gravitee.management.model.UserEntity)4 Subscription (io.gravitee.repository.management.model.Subscription)4 Test (org.junit.Test)4 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)4 NewExternalUserEntity (io.gravitee.management.model.NewExternalUserEntity)3 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)3 JWTSigner (com.auth0.jwt.JWTSigner)2 RoleEntity (io.gravitee.management.model.RoleEntity)2 UpdateUserEntity (io.gravitee.management.model.UpdateUserEntity)2 IOException (java.io.IOException)2 ServletException (javax.servlet.ServletException)2 Cookie (javax.servlet.http.Cookie)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2