Java举例梳理用户 赋予角色 角色授权 新增接口权限 可以使用新增用户正常登录访问受保护接口
时间: 2023-09-22 10:06:43 浏览: 70
1. 新增用户
```
public class User {
private String username;
private String password;
// ...其他属性
public User(String username, String password) {
this.username = username;
this.password = password;
}
// ...getter和setter方法
}
```
2. 赋予角色
```
public class Role {
private String name;
private List<Permission> permissions;
// ...其他属性
public Role(String name, List<Permission> permissions) {
this.name = name;
this.permissions = permissions;
}
// ...getter和setter方法
}
```
3. 角色授权
```
public class Permission {
private String name;
// ...其他属性
public Permission(String name) {
this.name = name;
}
// ...getter和setter方法
}
public class Authorization {
private Map<Role, List<Permission>> permissions;
public Authorization() {
permissions = new HashMap<>();
}
public void grantPermission(Role role, Permission permission) {
List<Permission> rolePermissions = permissions.get(role);
if (rolePermissions == null) {
rolePermissions = new ArrayList<>();
permissions.put(role, rolePermissions);
}
rolePermissions.add(permission);
}
public boolean hasPermission(Role role, Permission permission) {
List<Permission> rolePermissions = permissions.get(role);
return rolePermissions != null && rolePermissions.contains(permission);
}
}
```
4. 新增接口权限
```
public class ApiPermission extends Permission {
public ApiPermission(String name) {
super(name);
}
}
```
5. 受保护接口
```
public class ProtectedApi {
private Authorization authorization;
public ProtectedApi(Authorization authorization) {
this.authorization = authorization;
}
public void doSomething(User user) {
Role userRole = getUserRole(user);
if (authorization.hasPermission(userRole, new ApiPermission("doSomething"))) {
// 执行受保护操作
} else {
throw new SecurityException("User is not authorized to perform this action");
}
}
private Role getUserRole(User user) {
// 获取用户角色
return new Role("user", Collections.singletonList(new ApiPermission("doSomething")));
}
}
```
6. 使用新增用户正常登录访问受保护接口
```
public class Main {
public static void main(String[] args) {
User user = new User("username", "password");
Role userRole = new Role("user", Collections.singletonList(new ApiPermission("doSomething")));
Authorization authorization = new Authorization();
authorization.grantPermission(userRole, new ApiPermission("doSomething"));
ProtectedApi protectedApi = new ProtectedApi(authorization);
// 用户登录并访问受保护接口
protectedApi.doSomething(user);
}
}
```
以上是一个简单的用户授权和角色管理的示例,其中使用了 Java 编程语言来实现。
阅读全文