shiro使用
依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
配置
在src目录下新建resource/shori.ini文件,并在其中进行配置
# 用户
[users]
root=123,role1,role2
tom=123,role3
#权限
#角色
[roles]
role1=user:create,user:update
role2=user:delete
role3=user:create
测试代码
package com.qst;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) {
//1. 加载 INI 配置
IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2。创建 SecurityManager
SecurityManager securityManager = factory.getInstance();
//3. 使其可访问
SecurityUtils.setSecurityManager(securityManager);
//4. 通过Subject(验证工具) 用户名/密码身份验证token
Subject subject = SecurityUtils.getSubject();
// 创建一个用户(token)
UsernamePasswordToken token = new UsernamePasswordToken("root", "123");
token.setRememberMe(true);
// 登录
try{
// 验证身份信息,不通过就会抛出异常,身份认证没有抛出异常,表示登录成功
subject.login(token);
String currentUser = subject.getPrincipal().toString();
System.out.println("当前登录的用户:" + currentUser);
// 角色
boolean isRole = subject.hasRole("role3");
System.out.println("当前登录的用户是否有role2角色:" + isRole);
// 权限判断
boolean isPer = subject.isPermitted("user:delete");
System.out.println("当前登录的用户是否有user:delete角色:" +isPer);
// 退出
subject.logout();
} catch (UnknownAccountException uae){
System.out.println("用户名不存在");
} catch (IncorrectCredentialsException ice){
System.out.println("密码错误");
} catch (LockedAccountException lae) {
System.out.println("用户被锁定,不能登录");
} catch (AuthenticationException ae){
System.out.println("严重错误");
}
}
}