Search in sources :

Example 6 with UserDetails

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

the class AuthenticationSuccessListener method onApplicationEvent.

@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
    final UserDetails details = (UserDetails) event.getAuthentication().getPrincipal();
    try {
        UserEntity registeredUser = userService.findByUsername(details.getUsername(), false);
        // Principal username is the technical identifier of the user
        details.setUsername(registeredUser.getId());
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setUsername(details.getUsername());
        newUser.setSource(details.getSource());
        newUser.setSourceId(details.getSourceId());
        newUser.setFirstname(details.getFirstname());
        newUser.setLastname(details.getLastname());
        newUser.setEmail(details.getEmail());
        boolean addDefaultRole = false;
        if (event.getAuthentication().getAuthorities() == null || event.getAuthentication().getAuthorities().isEmpty()) {
            addDefaultRole = true;
        }
        UserEntity createdUser = userService.create(newUser, addDefaultRole);
        // Principal username is the technical identifier of the user
        details.setUsername(createdUser.getId());
        if (!addDefaultRole) {
            addRole(RoleScope.MANAGEMENT, createdUser.getId(), event.getAuthentication().getAuthorities());
            addRole(RoleScope.PORTAL, createdUser.getId(), event.getAuthentication().getAuthorities());
        }
    }
    userService.connect(details.getUsername());
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) UserEntity(io.gravitee.management.model.UserEntity)

Example 7 with UserDetails

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

the class GoogleAuthenticationResource method processUser.

private Response processUser(final Map<String, Object> userInfo) {
    String username = (String) userInfo.get("email");
    // set user to Authentication Context
    UserDetails userDetails = new UserDetails(username, "", Collections.emptyList());
    userDetails.setEmail(username);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()));
    try {
        UserEntity registeredUser = userService.findByUsername(username, false);
        userDetails.setUsername(registeredUser.getId());
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setUsername(username);
        newUser.setSource(AuthenticationSource.GOOGLE.getName());
        newUser.setSourceId(userInfo.get("sub").toString());
        newUser.setFirstname(userInfo.get("given_name").toString());
        newUser.setLastname(userInfo.get("family_name").toString());
        newUser.setEmail(username);
        UserEntity createdUser = userService.create(newUser, true);
        userDetails.setUsername(createdUser.getId());
    }
    // User refresh
    UpdateUserEntity user = new UpdateUserEntity();
    user.setUsername(username);
    user.setPicture(userInfo.get("picture").toString());
    userService.update(user);
    return connectUser(userDetails.getUsername());
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) UpdateUserEntity(io.gravitee.management.model.UpdateUserEntity) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserEntity(io.gravitee.management.model.UserEntity) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) UpdateUserEntity(io.gravitee.management.model.UpdateUserEntity)

Example 8 with UserDetails

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

the class AbstractAuthenticationResource method connectUser.

protected Response connectUser(String userId) {
    UserEntity user = userService.connect(userId);
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    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()));
    }
    // JWT signer
    final Map<String, Object> claims = new HashMap<>();
    claims.put(JWTHelper.Claims.ISSUER, environment.getProperty("jwt.issuer", JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER));
    claims.put(JWTHelper.Claims.SUBJECT, user.getId());
    claims.put(JWTHelper.Claims.PERMISSIONS, authorities);
    claims.put(JWTHelper.Claims.EMAIL, user.getEmail());
    claims.put(JWTHelper.Claims.FIRSTNAME, user.getFirstname());
    claims.put(JWTHelper.Claims.LASTNAME, user.getLastname());
    final JWTSigner.Options options = new JWTSigner.Options();
    options.setExpirySeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER));
    options.setIssuedAt(true);
    options.setJwtId(true);
    return Response.ok().entity(user).cookie(new NewCookie(HttpHeaders.AUTHORIZATION, "Bearer " + new JWTSigner(environment.getProperty("jwt.secret")).sign(claims, options), environment.getProperty("jwt.cookie-path", "/"), environment.getProperty("jwt.cookie-domain"), "", environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER), environment.getProperty("jwt.cookie-secure", Boolean.class, false), true)).build();
}
Also used : HashMap(java.util.HashMap) JWTSigner(com.auth0.jwt.JWTSigner) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserEntity(io.gravitee.management.model.UserEntity) 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) HashSet(java.util.HashSet) NewCookie(javax.ws.rs.core.NewCookie)

Example 9 with UserDetails

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

the class GitHubAuthenticationResource method processUser.

private Response processUser(final Map<String, Object> userInfo) {
    String username = (String) userInfo.get("email");
    if (username == null) {
        throw new BadRequestException("No public email linked to your GitHub account");
    }
    // set user to Authentication Context
    UserDetails userDetails = new UserDetails(username, "", Collections.emptyList());
    userDetails.setEmail(username);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()));
    try {
        UserEntity registeredUser = userService.findByUsername(username, false);
        userDetails.setUsername(registeredUser.getId());
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setUsername(username);
        newUser.setSource(AuthenticationSource.GITHUB.getName());
        newUser.setSourceId(userInfo.get("id").toString());
        String[] partNames = userInfo.get("name").toString().split(" ");
        newUser.setLastname(partNames[0]);
        newUser.setFirstname(partNames[1]);
        newUser.setEmail(username);
        UserEntity createdUser = userService.create(newUser, true);
        userDetails.setUsername(createdUser.getId());
    }
    // User refresh
    UpdateUserEntity user = new UpdateUserEntity();
    user.setUsername(username);
    user.setPicture(userInfo.get("avatar_url").toString());
    userService.update(user);
    return connectUser(userDetails.getUsername());
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) UpdateUserEntity(io.gravitee.management.model.UpdateUserEntity) BadRequestException(javax.ws.rs.BadRequestException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserEntity(io.gravitee.management.model.UserEntity) NewExternalUserEntity(io.gravitee.management.model.NewExternalUserEntity) UpdateUserEntity(io.gravitee.management.model.UpdateUserEntity)

Example 10 with UserDetails

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

the class OAuth2AuthenticationResource method processUser.

private Response processUser(String userInfo) throws IOException {
    HashMap<String, String> attrs = getUserProfileAttrs(userInfo);
    List<ExpressionMapping> mappings = serverConfiguration.getGroupsMapping();
    String username = attrs.get(UserProfile.EMAIL);
    if (username == null) {
        throw new BadRequestException("No public email linked to your account");
    }
    // set user to Authentication Context
    UserDetails userDetails = new UserDetails(username, "", Collections.emptyList());
    userDetails.setEmail(username);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()));
    try {
        UserEntity registeredUser = userService.findByUsername(username, false);
        userDetails.setUsername(registeredUser.getId());
    } catch (UserNotFoundException unfe) {
        final NewExternalUserEntity newUser = new NewExternalUserEntity();
        newUser.setUsername(username);
        newUser.setEmail(username);
        newUser.setSource(AuthenticationSource.OAUTH2.getName());
        if (attrs.get(UserProfile.ID) != null) {
            newUser.setSourceId(attrs.get(UserProfile.ID));
        }
        if (attrs.get(UserProfile.LASTNAME) != null) {
            newUser.setLastname(attrs.get(UserProfile.LASTNAME));
        }
        if (attrs.get(UserProfile.FIRSTNAME) != null) {
            newUser.setFirstname(attrs.get(UserProfile.FIRSTNAME));
        }
        if (attrs.get(UserProfile.PICTURE) != null) {
            newUser.setPicture(attrs.get(UserProfile.PICTURE));
        }
        if (!mappings.isEmpty()) {
            // can fail if a group in config does not exist in gravitee --> HTTP 500
            Set<GroupEntity> groupsToAdd = getGroupsToAddUser(username, mappings, userInfo);
            UserEntity createdUser = userService.create(newUser, true);
            userDetails.setUsername(createdUser.getId());
            addUserToApiAndAppGroupsWithDefaultRole(createdUser.getId(), groupsToAdd);
        } else {
            UserEntity createdUser = userService.create(newUser, true);
            userDetails.setUsername(createdUser.getId());
        }
    }
    // User refresh
    UpdateUserEntity user = new UpdateUserEntity();
    user.setUsername(username);
    if (attrs.get(UserProfile.LASTNAME) != null) {
        user.setLastname(attrs.get(UserProfile.LASTNAME));
    }
    if (attrs.get(UserProfile.FIRSTNAME) != null) {
        user.setFirstname(attrs.get(UserProfile.FIRSTNAME));
    }
    if (attrs.get(UserProfile.PICTURE) != null) {
        user.setPicture(attrs.get(UserProfile.PICTURE));
    }
    UserEntity updatedUser = userService.update(user);
    return connectUser(updatedUser.getId());
}
Also used : UserNotFoundException(io.gravitee.management.service.exceptions.UserNotFoundException) ExpressionMapping(io.gravitee.management.rest.resource.auth.oauth2.ExpressionMapping) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

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