Shiro学习,这一篇就够了

权限认证主要步骤:实现本身的MyRealm(继承AuthorizingRealm),重写认证方法:doGetAuthenticationInfo和受权方法:doGetAuthorizationInfo;app

doGetAuthenticationInfo示例: ide

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("token.getPrincipal:" + token.getPrincipal());
        System.out.println("token.getCredentials:" + token.getCredentials());
        String userName = token.getPrincipal().toString();
        User user = userDao.getUserByUserName(userName);
        if (user != null) {
            // Object principal, Object credentials, String realmName
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
            return authcInfo;
        } else {
            return null;
        }
    }

doGetAuthorizationInfo示例:ui

 @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        if ("".equals(userName)) {
            return  null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,"123456",this.getName());
        return info;
    }

doGetAuthorizationInfo这里是简单示例,其实就是把用户的信息放进去,例如用户的角色list,权限list;this

后台权限控制:url

@RequiresPermissions({"delete"}) //须要有delete权限;没有的话 AuthorizationException
    @PostMapping("/delete")
    public Map<String, Object> deletePermission() {
        System.out.println("delete");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        map.put("msg", "当前角色有删除的权力");
        return map;
    }

    @RequiresRoles({"vip"}) //须要有vip角色,没有的话 AuthorizationException
    @PostMapping("/vip")
    public Map<String, Object> vipRole() {
        System.out.println("vip");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        map.put("msg", "当前用户具备 vip 角色");
        return map;
    }

固然还须要配置shiro,好比shiroFilter,配置哪些路径须要认证,哪些无需认证(好比登入登出):其余具体细节可访问最下面的连接;.net

注:① authc:全部url都必须认证经过才能够访问; ② anon:全部url都均可以匿名访问blog

参考文章:  https://blog.csdn.net/larger5/article/details/79838212(@Configuration配置类方式配置)继承

shiroFilter配置详解: https://blog.csdn.net/zhangcc233/article/details/80591769    token

相关文章
相关标签/搜索