Search in sources :

Example 1 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.

the class InMemoryGraviteeUserDetailsManager method loadUserByUsername.

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDetails user = users.get(username.toLowerCase());
    if (user == null) {
        throw new UsernameNotFoundException(username);
    }
    // return a copy of the user 'cause spring will erase credentials in the security process
    UserDetails userDetails = new UserDetails(user.getUsername(), user.getPassword(), user.getEmail(), user.getAuthorities());
    userDetails.setSource(InMemoryIdentityProvider.PROVIDER_TYPE);
    userDetails.setSourceId(user.getUsername());
    userDetails.setFirstname(user.getFirstname());
    userDetails.setLastname(user.getLastname());
    return userDetails;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails)

Example 2 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.

the class InMemoryGraviteeUserDetailsManager method convert.

private UserDetails convert(org.springframework.security.core.userdetails.UserDetails user) {
    if (user instanceof UserDetails) {
        return (UserDetails) user;
    }
    UserDetails userDetails = new UserDetails(user.getUsername(), user.getPassword(), user.getAuthorities());
    userDetails.setSource(InMemoryIdentityProvider.PROVIDER_TYPE);
    userDetails.setSourceId(user.getUsername());
    if (user instanceof io.gravitee.rest.api.idp.api.authentication.UserDetails) {
        userDetails.setFirstname(((io.gravitee.rest.api.idp.api.authentication.UserDetails) user).getFirstname());
        userDetails.setLastname(((io.gravitee.rest.api.idp.api.authentication.UserDetails) user).getLastname());
    }
    return userDetails;
}
Also used : UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails)

Example 3 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails in project gravitee-management-rest-api by gravitee-io.

the class AuditServiceImpl method createAuditLog.

@Async
@Override
public void createAuditLog(Audit.AuditReferenceType referenceType, String referenceId, Map<Audit.AuditProperties, String> properties, Audit.AuditEvent event, Date createdAt, Object oldValue, Object newValue) {
    Audit audit = new Audit();
    audit.setId(UuidString.generateRandom());
    audit.setCreatedAt(createdAt == null ? new Date() : createdAt);
    final UserDetails authenticatedUser = getAuthenticatedUser();
    final String user;
    if (authenticatedUser != null && "token".equals(authenticatedUser.getSource())) {
        user = userService.findById(authenticatedUser.getUsername()).getDisplayName() + " - (using token \"" + authenticatedUser.getSourceId() + "\")";
    } else {
        user = getAuthenticatedUsernameOrSystem();
    }
    audit.setUser(user);
    if (properties != null) {
        Map<String, String> stringStringMap = new HashMap<>(properties.size());
        properties.forEach((auditProperties, s) -> stringStringMap.put(auditProperties.name(), s));
        audit.setProperties(stringStringMap);
    }
    audit.setReferenceType(referenceType);
    audit.setReferenceId(referenceId);
    audit.setEvent(event.name());
    ObjectNode oldNode = oldValue == null ? mapper.createObjectNode() : mapper.convertValue(oldValue, ObjectNode.class).remove(Arrays.asList("updatedAt", "createdAt"));
    ObjectNode newNode = newValue == null ? mapper.createObjectNode() : mapper.convertValue(newValue, ObjectNode.class).remove(Arrays.asList("updatedAt", "createdAt"));
    audit.setPatch(JsonDiff.asJson(oldNode, newNode).toString());
    try {
        auditRepository.create(audit);
    } catch (TechnicalException e) {
        LOGGER.error("Error occurs during the creation of an Audit Log {}.", e);
    }
}
Also used : UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) UuidString(io.gravitee.rest.api.service.common.UuidString) Async(org.springframework.scheduling.annotation.Async)

Example 4 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails 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
}
Also used : Cookie(javax.servlet.http.Cookie) Response(javax.ws.rs.core.Response) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) Token(io.gravitee.rest.api.portal.rest.model.Token) Test(org.junit.Test)

Example 5 with UserDetails

use of io.gravitee.rest.api.idp.api.authentication.UserDetails 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();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) Duration(java.time.Duration) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuth2AuthenticationResource(io.gravitee.rest.api.portal.rest.resource.auth.OAuth2AuthenticationResource) Token(io.gravitee.rest.api.portal.rest.model.Token) TokenTypeEnum(io.gravitee.rest.api.portal.rest.model.Token.TokenTypeEnum) Instant(java.time.Instant) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) Maps(io.gravitee.common.util.Maps) RoleEntity(io.gravitee.rest.api.model.RoleEntity) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) MediaType(io.gravitee.common.http.MediaType) Response(javax.ws.rs.core.Response) ResourceContext(javax.ws.rs.container.ResourceContext) Response.ok(javax.ws.rs.core.Response.ok) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Token(io.gravitee.rest.api.portal.rest.model.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

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