Search in sources :

Example 1 with RoleEntity

use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.

the class AbstractAuthenticationResource method connectUserInternal.

protected Response connectUserInternal(UserEntity user, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    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> userRoles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getId());
    if (!userRoles.isEmpty()) {
        userRoles.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(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
    final TokenEntity tokenEntity = new TokenEntity();
    tokenEntity.setType(BEARER);
    tokenEntity.setToken(token);
    if (idToken != null) {
        tokenEntity.setAccessToken(accessToken);
        tokenEntity.setIdToken(idToken);
    }
    if (state != null && !state.isEmpty()) {
        tokenEntity.setState(state);
    }
    final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
    servletResponse.addCookie(bearerCookie);
    return Response.ok(tokenEntity).build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) NotBlank(javax.validation.constraints.NotBlank) BEARER(io.gravitee.rest.api.management.rest.model.TokenType.BEARER) 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) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) UserService(io.gravitee.rest.api.service.UserService) Duration(java.time.Duration) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) MembershipService(io.gravitee.rest.api.service.MembershipService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) 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) Response(javax.ws.rs.core.Response) TokenAuthenticationFilter(io.gravitee.rest.api.security.filter.TokenAuthenticationFilter) Environment(org.springframework.core.env.Environment) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) UserEntity(io.gravitee.rest.api.model.UserEntity) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) 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) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity)

Example 2 with RoleEntity

use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.

the class AuthoritiesProviderTest method shouldGenerateAuthorities.

@Test
public void shouldGenerateAuthorities() {
    final String USER_ID = "userid1";
    final RoleEntity portalRole = new RoleEntity();
    portalRole.setId("PORTAL_ROLE");
    portalRole.setName("PORTAL_ROLE");
    portalRole.setScope(RoleScope.ENVIRONMENT);
    final RoleEntity mgtRole1 = new RoleEntity();
    mgtRole1.setId("MGT_ROLE1");
    mgtRole1.setName("MGT_ROLE1");
    mgtRole1.setScope(RoleScope.ORGANIZATION);
    final RoleEntity mgtRole2 = new RoleEntity();
    mgtRole2.setId("MGT_ROLE2");
    mgtRole2.setName("MGT_ROLE2");
    mgtRole2.setScope(RoleScope.ORGANIZATION);
    when(membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, "DEFAULT", MembershipMemberType.USER, USER_ID)).thenReturn(new HashSet<>(asList(portalRole)));
    when(membershipService.getRoles(MembershipReferenceType.ORGANIZATION, "DEFAULT", MembershipMemberType.USER, USER_ID)).thenReturn(new HashSet<>(asList(mgtRole1, mgtRole2)));
    final Set<GrantedAuthority> grantedAuthorities = cut.retrieveAuthorities(USER_ID);
    assertEquals(3, grantedAuthorities.size());
    final List<GrantedAuthority> expected = AuthorityUtils.commaSeparatedStringToAuthorityList("ENVIRONMENT:PORTAL_ROLE,ORGANIZATION:MGT_ROLE1,ORGANIZATION:MGT_ROLE2");
    assertTrue(grantedAuthorities.containsAll(expected));
}
Also used : RoleEntity(io.gravitee.rest.api.model.RoleEntity) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.Test)

Example 3 with RoleEntity

use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.

the class MembershipCommandHandler method handle.

@Override
public Single<MembershipReply> handle(MembershipCommand command) {
    MembershipPayload membershipPayload = command.getPayload();
    GraviteeContext.setCurrentOrganization(membershipPayload.getOrganizationId());
    try {
        RoleScope roleScope;
        MembershipReferenceType membershipReferenceType;
        try {
            roleScope = RoleScope.valueOf(membershipPayload.getReferenceType());
            membershipReferenceType = MembershipReferenceType.valueOf(membershipPayload.getReferenceType());
        } catch (Exception e) {
            logger.error("Invalid referenceType [{}].", membershipPayload.getReferenceType());
            return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
        }
        final UserEntity userEntity = userService.findBySource(COCKPIT_SOURCE, membershipPayload.getUserId(), false);
        final RoleEntity roleEntity = findRole(roleScope, membershipPayload.getRole());
        final MembershipService.MembershipReference membershipReference = new MembershipService.MembershipReference(membershipReferenceType, membershipPayload.getReferenceId());
        final MembershipService.MembershipMember membershipMember = new MembershipService.MembershipMember(userEntity.getId(), null, MembershipMemberType.USER);
        final MembershipService.MembershipRole membershipRole = new MembershipService.MembershipRole(roleEntity.getScope(), roleEntity.getName());
        membershipService.updateRolesToMemberOnReference(membershipReference, membershipMember, Collections.singletonList(membershipRole), COCKPIT_SOURCE, false);
        logger.info("Role [{}] assigned on {} [{}] for user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), userEntity.getId(), membershipPayload.getOrganizationId());
        return Single.just(new MembershipReply(command.getId(), CommandStatus.SUCCEEDED));
    } catch (Exception e) {
        logger.error("Error occurred when trying to assign role [{}] on {} [{}] for cockpit user [{}] and organization [{}].", membershipPayload.getRole(), membershipPayload.getReferenceType(), membershipPayload.getReferenceId(), membershipPayload.getUserId(), membershipPayload.getOrganizationId(), e);
        return Single.just(new MembershipReply(command.getId(), CommandStatus.ERROR));
    } finally {
        GraviteeContext.cleanContext();
    }
}
Also used : MembershipReply(io.gravitee.cockpit.api.command.membership.MembershipReply) RoleNotFoundException(io.gravitee.rest.api.service.exceptions.RoleNotFoundException) UserEntity(io.gravitee.rest.api.model.UserEntity) RoleEntity(io.gravitee.rest.api.model.RoleEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) MembershipService(io.gravitee.rest.api.service.MembershipService) MembershipPayload(io.gravitee.cockpit.api.command.membership.MembershipPayload) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType)

Example 4 with RoleEntity

use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.

the class MembershipService_GetMemberPermissionsTest method shouldGetPermissionsIfMemberOfApi.

@Test
public void shouldGetPermissionsIfMemberOfApi() throws Exception {
    ApiEntity api = mock(ApiEntity.class);
    doReturn(API_ID).when(api).getId();
    doReturn(Collections.emptySet()).when(api).getGroups();
    doReturn(api).when(apiService).findById(API_ID);
    Membership membership = mock(Membership.class);
    doReturn("API_" + ROLENAME).when(membership).getRoleId();
    doReturn(new HashSet<>(asList(membership))).when(membershipRepository).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.API, API_ID);
    UserEntity userEntity = mock(UserEntity.class);
    doReturn(userEntity).when(userService).findById(USERNAME);
    RoleEntity roleEntity = mock(RoleEntity.class);
    Map<String, char[]> rolePerms = new HashMap<>();
    rolePerms.put(ApiPermission.DOCUMENTATION.getName(), new char[] { RolePermissionAction.UPDATE.getId(), RolePermissionAction.CREATE.getId() });
    doReturn(rolePerms).when(roleEntity).getPermissions();
    doReturn(roleEntity).when(roleService).findById("API_" + ROLENAME);
    Map<String, char[]> permissions = membershipService.getUserMemberPermissions(api, USERNAME);
    assertNotNull(permissions);
    assertPermissions(rolePerms, permissions);
    verify(membershipRepository, times(1)).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.API, API_ID);
    verify(membershipRepository, never()).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.GROUP, GROUP_ID1);
    verify(apiService, times(1)).findById(API_ID);
    verify(userService, times(1)).findById(USERNAME);
    verify(roleService, times(1)).findById("API_" + ROLENAME);
}
Also used : RoleEntity(io.gravitee.rest.api.model.RoleEntity) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Membership(io.gravitee.repository.management.model.Membership) UserEntity(io.gravitee.rest.api.model.UserEntity) Test(org.junit.Test)

Example 5 with RoleEntity

use of io.gravitee.rest.api.model.RoleEntity in project gravitee-management-rest-api by gravitee-io.

the class MembershipService_GetMemberPermissionsTest method shouldGetMergedPermissionsIfMemberOfApiAndApiGroup.

@Test
public void shouldGetMergedPermissionsIfMemberOfApiAndApiGroup() throws Exception {
    ApiEntity api = mock(ApiEntity.class);
    doReturn(API_ID).when(api).getId();
    doReturn(Collections.singleton(GROUP_ID1)).when(api).getGroups();
    doReturn(api).when(apiService).findById(API_ID);
    Membership membershipUser = mock(Membership.class);
    doReturn("API_" + ROLENAME).when(membershipUser).getRoleId();
    doReturn(new HashSet<>(asList(membershipUser))).when(membershipRepository).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.API, API_ID);
    Membership membershipGroup = mock(Membership.class);
    doReturn("API_" + ROLENAME2).when(membershipGroup).getRoleId();
    doReturn(new HashSet<>(asList(membershipGroup))).when(membershipRepository).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.GROUP, GROUP_ID1);
    UserEntity userEntity = mock(UserEntity.class);
    doReturn(userEntity).when(userService).findById(USERNAME);
    RoleEntity roleEntity = mock(RoleEntity.class);
    Map<String, char[]> rolePerms = new HashMap<>();
    rolePerms.put(ApiPermission.DOCUMENTATION.getName(), new char[] { RolePermissionAction.UPDATE.getId(), RolePermissionAction.CREATE.getId() });
    doReturn(rolePerms).when(roleEntity).getPermissions();
    doReturn(roleEntity).when(roleService).findById("API_" + ROLENAME);
    RoleEntity roleEntity2 = mock(RoleEntity.class);
    Map<String, char[]> rolePerms2 = new HashMap<>();
    rolePerms2.put(ApiPermission.DOCUMENTATION.getName(), new char[] { RolePermissionAction.READ.getId(), RolePermissionAction.DELETE.getId() });
    rolePerms2.put(ApiPermission.PLAN.getName(), new char[] { RolePermissionAction.READ.getId() });
    doReturn(rolePerms2).when(roleEntity2).getPermissions();
    doReturn(RoleScope.API).when(roleEntity2).getScope();
    doReturn(roleEntity2).when(roleService).findById("API_" + ROLENAME2);
    Map<String, char[]> permissions = membershipService.getUserMemberPermissions(api, USERNAME);
    assertNotNull(permissions);
    Map<String, char[]> expectedPermissions = new HashMap<>();
    expectedPermissions.put(ApiPermission.DOCUMENTATION.getName(), new char[] { RolePermissionAction.CREATE.getId(), RolePermissionAction.READ.getId(), RolePermissionAction.UPDATE.getId(), RolePermissionAction.DELETE.getId() });
    expectedPermissions.put(ApiPermission.PLAN.getName(), new char[] { RolePermissionAction.READ.getId() });
    assertPermissions(expectedPermissions, permissions);
    verify(membershipRepository, times(1)).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.API, API_ID);
    verify(membershipRepository, times(1)).findByMemberIdAndMemberTypeAndReferenceTypeAndReferenceId(USERNAME, MembershipMemberType.USER, MembershipReferenceType.GROUP, GROUP_ID1);
    verify(apiService, times(1)).findById(API_ID);
    verify(userService, times(1)).findById(USERNAME);
    verify(roleService, times(1)).findById("API_" + ROLENAME);
    verify(roleService, times(1)).findById("API_" + ROLENAME2);
}
Also used : RoleEntity(io.gravitee.rest.api.model.RoleEntity) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) Membership(io.gravitee.repository.management.model.Membership) UserEntity(io.gravitee.rest.api.model.UserEntity) Test(org.junit.Test)

Aggregations

RoleEntity (io.gravitee.rest.api.model.RoleEntity)29 Test (org.junit.Test)20 UserEntity (io.gravitee.rest.api.model.UserEntity)13 Membership (io.gravitee.repository.management.model.Membership)8 MembershipService (io.gravitee.rest.api.service.MembershipService)7 Role (io.gravitee.repository.management.model.Role)6 MembershipPayload (io.gravitee.cockpit.api.command.membership.MembershipPayload)5 MembershipReply (io.gravitee.cockpit.api.command.membership.MembershipReply)5 NewRoleEntity (io.gravitee.rest.api.model.NewRoleEntity)5 UpdateRoleEntity (io.gravitee.rest.api.model.UpdateRoleEntity)5 Response (javax.ws.rs.core.Response)5 MembershipCommand (io.gravitee.cockpit.api.command.membership.MembershipCommand)4 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)4 MembershipReferenceType (io.gravitee.rest.api.model.MembershipReferenceType)4 Instant (java.time.Instant)4 List (java.util.List)4 JWT (com.auth0.jwt.JWT)3 Algorithm (com.auth0.jwt.algorithms.Algorithm)3 Maps (io.gravitee.common.util.Maps)3 UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)3