Search in sources :

Example 1 with RoleInfo

use of com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo in project nacos by alibaba.

the class UserController method deleteUser.

/**
 * Delete an existed user.
 *
 * @param username username of user
 * @return ok if deleted succeed, keep silent if user not exist
 * @since 1.2.0
 */
@DeleteMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "users", action = ActionTypes.WRITE)
public Object deleteUser(@RequestParam String username) {
    List<RoleInfo> roleInfoList = roleService.getRoles(username);
    if (roleInfoList != null) {
        for (RoleInfo roleInfo : roleInfoList) {
            if (roleInfo.getRole().equals(AuthConstants.GLOBAL_ADMIN_ROLE)) {
                throw new IllegalArgumentException("cannot delete admin: " + username);
            }
        }
    }
    userDetailsService.deleteUser(username);
    return RestResultUtils.success("delete user ok!");
}
Also used : RoleInfo(com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) Secured(com.alibaba.nacos.auth.annotation.Secured)

Example 2 with RoleInfo

use of com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo in project nacos by alibaba.

the class Role_ITCase method createDeleteQueryRole.

@Test
public void createDeleteQueryRole() {
    login();
    // Create a user:
    ResponseEntity<String> response = request("/nacos/v1/auth/users", Params.newParams().appendParam("username", "username2").appendParam("password", "password1").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Create a role:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", "role1").appendParam("username", "username2").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query role of user:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1").appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    Page<RoleInfo> roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {
    });
    Assert.assertNotNull(roleInfoPage);
    Assert.assertNotNull(roleInfoPage.getPageItems());
    boolean found = false;
    for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
        if (roleInfo.getRole().equals("role1")) {
            found = true;
            break;
        }
    }
    Assert.assertTrue(found);
    // Add second role to user:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", "role2").appendParam("username", "username2").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.POST);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query roles of user:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1").appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {
    });
    Assert.assertNotNull(roleInfoPage);
    Assert.assertNotNull(roleInfoPage.getPageItems());
    found = false;
    boolean found2 = false;
    for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
        if (roleInfo.getRole().equals("role1")) {
            found = true;
        }
        if (roleInfo.getRole().equals("role2")) {
            found2 = true;
        }
        if (found && found2) {
            break;
        }
    }
    Assert.assertTrue(found);
    Assert.assertTrue(found2);
    // Delete role:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", "role2").appendParam("username", "username2").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query roles of user:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1").appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {
    });
    Assert.assertNotNull(roleInfoPage);
    Assert.assertNotNull(roleInfoPage.getPageItems());
    found = false;
    found2 = false;
    for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
        if (roleInfo.getRole().equals("role1")) {
            found = true;
        }
        if (roleInfo.getRole().equals("role2")) {
            found2 = true;
        }
    }
    Assert.assertFalse(found2);
    Assert.assertTrue(found);
    // Delete role:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("role", "role1").appendParam("username", "username2").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.DELETE);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    // Query roles of user:
    response = request("/nacos/v1/auth/roles", Params.newParams().appendParam("username", "username2").appendParam("pageNo", "1").appendParam("pageSize", "10").appendParam("accessToken", accessToken).done(), String.class, HttpMethod.GET);
    Assert.assertTrue(response.getStatusCode().is2xxSuccessful());
    roleInfoPage = JacksonUtils.toObj(response.getBody(), new TypeReference<Page<RoleInfo>>() {
    });
    Assert.assertNotNull(roleInfoPage);
    Assert.assertNotNull(roleInfoPage.getPageItems());
    found = false;
    found2 = false;
    for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
        if (roleInfo.getRole().equals("role1")) {
            found = true;
        }
        if (roleInfo.getRole().equals("role2")) {
            found2 = true;
        }
    }
    Assert.assertFalse(found2);
    Assert.assertFalse(found);
}
Also used : RoleInfo(com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo) Page(com.alibaba.nacos.config.server.model.Page) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HttpClient4Test(com.alibaba.nacos.test.base.HttpClient4Test) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 3 with RoleInfo

use of com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo in project nacos by alibaba.

the class NacosRoleServiceImpl method reload.

@Scheduled(initialDelay = 5000, fixedDelay = 15000)
private void reload() {
    try {
        Page<RoleInfo> roleInfoPage = rolePersistService.getRolesByUserName(StringUtils.EMPTY, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
        if (roleInfoPage == null) {
            return;
        }
        Set<String> tmpRoleSet = new HashSet<>(16);
        Map<String, List<RoleInfo>> tmpRoleInfoMap = new ConcurrentHashMap<>(16);
        for (RoleInfo roleInfo : roleInfoPage.getPageItems()) {
            if (!tmpRoleInfoMap.containsKey(roleInfo.getUsername())) {
                tmpRoleInfoMap.put(roleInfo.getUsername(), new ArrayList<>());
            }
            tmpRoleInfoMap.get(roleInfo.getUsername()).add(roleInfo);
            tmpRoleSet.add(roleInfo.getRole());
        }
        Map<String, List<PermissionInfo>> tmpPermissionInfoMap = new ConcurrentHashMap<>(16);
        for (String role : tmpRoleSet) {
            Page<PermissionInfo> permissionInfoPage = permissionPersistService.getPermissions(role, DEFAULT_PAGE_NO, Integer.MAX_VALUE);
            tmpPermissionInfoMap.put(role, permissionInfoPage.getPageItems());
        }
        roleSet = tmpRoleSet;
        roleInfoMap = tmpRoleInfoMap;
        permissionInfoMap = tmpPermissionInfoMap;
    } catch (Exception e) {
        Loggers.AUTH.warn("[LOAD-ROLES] load failed", e);
    }
}
Also used : PermissionInfo(com.alibaba.nacos.plugin.auth.impl.persistence.PermissionInfo) RoleInfo(com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo) ArrayList(java.util.ArrayList) List(java.util.List) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashSet(java.util.HashSet) ConcurrentHashSet(com.alibaba.nacos.common.utils.ConcurrentHashSet) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Example 4 with RoleInfo

use of com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo in project nacos by alibaba.

the class NacosRoleServiceImpl method hasPermission.

/**
 * Determine if the user has permission of the resource.
 *
 * <p>Note if the user has many roles, this method returns true if any one role of the user has the desired
 * permission.
 *
 * @param username   user info
 * @param permission permission to auth
 * @return true if granted, false otherwise
 */
public boolean hasPermission(String username, Permission permission) {
    // update password
    if (AuthConstants.UPDATE_PASSWORD_ENTRY_POINT.equals(permission.getResource().getName())) {
        return true;
    }
    List<RoleInfo> roleInfoList = getRoles(username);
    if (Collections.isEmpty(roleInfoList)) {
        return false;
    }
    // Global admin pass:
    for (RoleInfo roleInfo : roleInfoList) {
        if (AuthConstants.GLOBAL_ADMIN_ROLE.equals(roleInfo.getRole())) {
            return true;
        }
    }
    // Old global admin can pass resource 'console/':
    if (permission.getResource().getName().startsWith(AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX)) {
        return false;
    }
    // For other roles, use a pattern match to decide if pass or not.
    for (RoleInfo roleInfo : roleInfoList) {
        List<PermissionInfo> permissionInfoList = getPermissions(roleInfo.getRole());
        if (Collections.isEmpty(permissionInfoList)) {
            continue;
        }
        for (PermissionInfo permissionInfo : permissionInfoList) {
            String permissionResource = permissionInfo.getResource().replaceAll("\\*", ".*");
            String permissionAction = permissionInfo.getAction();
            if (permissionAction.contains(permission.getAction()) && Pattern.matches(permissionResource, joinResource(permission.getResource()))) {
                return true;
            }
        }
    }
    return false;
}
Also used : PermissionInfo(com.alibaba.nacos.plugin.auth.impl.persistence.PermissionInfo) RoleInfo(com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo)

Example 5 with RoleInfo

use of com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo in project nacos by alibaba.

the class NacosAuthManager method getNacosUser.

private NacosUser getNacosUser(String token) {
    Authentication authentication = tokenManager.getAuthentication(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    String username = authentication.getName();
    NacosUser user = new NacosUser();
    user.setUserName(username);
    user.setToken(token);
    List<RoleInfo> roleInfoList = roleService.getRoles(username);
    if (roleInfoList != null) {
        for (RoleInfo roleInfo : roleInfoList) {
            if (roleInfo.getRole().equals(AuthConstants.GLOBAL_ADMIN_ROLE)) {
                user.setGlobalAdmin(true);
                break;
            }
        }
    }
    return user;
}
Also used : NacosUser(com.alibaba.nacos.plugin.auth.impl.users.NacosUser) RoleInfo(com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo) Authentication(org.springframework.security.core.Authentication)

Aggregations

RoleInfo (com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo)5 PermissionInfo (com.alibaba.nacos.plugin.auth.impl.persistence.PermissionInfo)2 Secured (com.alibaba.nacos.auth.annotation.Secured)1 ConcurrentHashSet (com.alibaba.nacos.common.utils.ConcurrentHashSet)1 Page (com.alibaba.nacos.config.server.model.Page)1 NacosUser (com.alibaba.nacos.plugin.auth.impl.users.NacosUser)1 HttpClient4Test (com.alibaba.nacos.test.base.HttpClient4Test)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 List (java.util.List)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Test (org.junit.Test)1 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)1 Scheduled (org.springframework.scheduling.annotation.Scheduled)1 Authentication (org.springframework.security.core.Authentication)1 DeleteMapping (org.springframework.web.bind.annotation.DeleteMapping)1