3、Shiro授权

Shiro授权过程和认证过程相似:

项目结构:

package com.shiro.shiroframe;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class ShiroAuthorizerTest {
    //realm,暂时用来存储我们假造的用户信息
    SimpleAccountRealm simpleAccountRealm=new SimpleAccountRealm();
    @BeforeEach
    public void setUserMsg(){
        //添加一个用户信息并设置角色为admin
        simpleAccountRealm.addAccount("houru","miyue","admin","user");//设置该用户既是管理员又是普通用户
    }
    @Test
    public void ShiroAuthorizerTest() {
        //构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //SecurityManager环境下设置realm
        defaultSecurityManager.setRealm(simpleAccountRealm);
        //SecurityUtils先获取SecurityManager环境
        SecurityUtils.setSecurityManager(defaultSecurityManager);
      //获取subject
        Subject subject= SecurityUtils.getSubject();
        //通过UsernamePasswordToken组织提交认证所要传递的参数
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("houru","miyue");
        //登录认证
        subject.login(usernamePasswordToken);
        //打印是否认证通过:subject.isAuthenticated()
        System.err.println(subject.isAuthenticated());
        //权限认证
        //检查当前用户是否具有admin角色权限
        subject.checkRole("admin");
        //检查当前用户是否具有admin,user等角色权限
        subject.checkRoles("admin","user");
    }
}

 

posted @ 2019-06-14 16:35  指尖下的世界  阅读(259)  评论(0编辑  收藏  举报
/* 看板娘 */ /*炸泡*/
/* 鼠标点击求赞文字特效 */