Shiro實現使用者授權

Hanyta發表於2024-05-18
  1. ShiroConfig中的getShiroFilterFactoryBean方法新增認證程式碼

    //授權,正常情況下,沒有授權會跳轉到為授權頁面
    filterMap.put("/user/add","perms[user:add]");
    filterMap.put("/user/update","perms[user:update]");
    
  2. 在controller中新增授權頁面

    @RequestMapping("/noauto")
    @ResponseBody
    public String unauthorized() {
        return "未經授權,無法訪問此頁面";
    }
    
  3. ShiroConfig中的getShiroFilterFactoryBean方法中新增

    //為授權頁面
    bean.setUnauthorizedUrl("/noauto");
    
  4. UserRealm類的修改

    //自定義的UserRealm
    public class UserRealm extends AuthorizingRealm {
    
        @Autowired
        UserService userService;
        //授權
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            System.out.println("執行了=>授權doGetAuthorizationInfo");
    
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    
            //拿到當前登入的這個物件
            Subject subject = SecurityUtils.getSubject();
            User currentUser = (User)subject.getPrincipal();//拿到user物件
    
            //設定當前使用者的許可權
            info.addStringPermission(currentUser.getPerms());
    
            return info;
        }
    
        //認證
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            ......
            // 密碼認證,shiro做
            return new SimpleAuthenticationInfo(user,user.getPwd(),"");
        }
    }
    

相關文章