ShiroController.java 2.68 KB
package com.myxrk.rbac.controller;

import com.myxrk.rbac.annotation.DataGrid;
import com.myxrk.rbac.po.Employee;
import com.myxrk.rbac.po.SysUser;
import com.myxrk.rbac.result.Result;
import com.myxrk.rbac.service.EmployeeService;
import com.myxrk.rbac.service.PermissionService;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/shiro")
public class ShiroController {

    @Resource
    private EmployeeService employeeService;

    @Resource
    private PermissionService permissionService;

    @GetMapping("/anon")
    public Result<String> anon() {
        return Result.success("不需要认证授权的url");
    }

    @GetMapping("/authentication")
    public Result<String> authentication() {
        return Result.success("认证成功");
    }

    @RequiresPermissions("sys:perm:read")
    @GetMapping("/permRead")
    public Result<String> permRead() {
        return Result.success("授权:读");
    }

    @RequiresPermissions("sys:perm:write")
    @GetMapping("/permWrite")
    public Result<String> permWrite() {
        return Result.success("授权:写");
    }

    @RequiresRoles("1")
    @GetMapping("/roleSys")
    public Result<String> roleSys() {
        return Result.success("授权:系统管理员");
    }

    @RequiresRoles("2")
    @GetMapping("/roleCom")
    public Result<String> roleCom() {
        return Result.success("授权:普通管理员");
    }

    //用户的信息
    @GetMapping("/info")
    public Result<String> info() {
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        boolean role1 = subject.hasRole("1");
        boolean role2 = subject.hasRole("2");
        boolean write = subject.isPermitted("sys:perm:write");
        boolean read = subject.isPermitted("sys:perm:read");

        String result = "[principal]:" + principal + " [write]:" + write + " [read]:" + read + " [role1]:" + role1 + " [role2]:" + role2;
        return Result.success(result);
    }

    @DataGrid("dg_emp_list_001")
    @GetMapping("/employees")
    public Result<Employee> getEmployees() {
        return Result.success(employeeService.getAllEmployees());
    }

    @DataGrid("dg_sys_user_list_001")
    @GetMapping("/users")
    public Result<SysUser> getUsers() {
        return Result.success(permissionService.getAllUsers());
    }
}