shiro中授权小示例

一、POM

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
</dependency>

二、INI

[users]
admin=123456,system
tom=123,role1,role2

[roles]
system=auth01,auth02,auth03
role1=auth02
role2=auth03

格式:
[users]
用户名=密码,角色1,角色2…
[roles]
角色名=权限1,权限2…

三、ShiroUtil

package com.yale;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class ShiroUtil {

    public static Subject login(String configPath, String username, String password) throws AuthenticationException{
        //1.由ini文件初始化一个Factory<SecurityManager>
        Factory<SecurityManager> factory = new IniSecurityManagerFactory(configPath);
        //2.从Factory中获取一个SecurityManager实例
        SecurityManager securityManager = factory.getInstance();
        //3.使用SecurityUtils工具类设值SecurityManager实例
        SecurityUtils.setSecurityManager(securityManager);
        //4.再从SecurityUtils中获取Subject
        Subject subject = SecurityUtils.getSubject();
        //5.调用Subject的login方法验证用户
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        subject.login(token);
        return subject;
    }

}

四、ShiroMain

package com.yale;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;

public class ShiroMain {
    public static void main(String[] args) {
        Subject subject = null;
        try {
            subject = ShiroUtil.login("classpath:shiro.ini","tom","123");
            System.out.println("验证成功!");

            //查看用户是否拥有给定角色
            boolean hasRole = subject.hasRole("role1");
            System.out.println("tom是否拥有role1:"+hasRole);

            //查看用户是否拥有给定权限
            boolean permitted = subject.isPermitted("auth02");
            System.out.println("tom是否拥有auth02:"+permitted);

        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("验证失败!");
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值