Shiro入门
2021-10-24 本文已影响0人
WebGiser
1635076374(1).png
image.png
1635076460(1).png
image.png
1635076460(1).png
1、项目结构
1635075856(1).png2、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>demo</artifactId>
<groupId>com.hello</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>shiro</artifactId>
<name>shiro</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3、读取静态文件的Realm方式
3.1、resources/shiro.ini
[users]
zhangsan=123
lisi=456
3.2、TestShiro.java
package com.hello;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
public class TestShiro {
public static void main(String[] args) {
//1.创建 SecurityManager
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//2、给安全管理器设置realm
Realm realm = new IniRealm("classpath:shiro.ini");
securityManager.setRealm(realm);
//3、SecurityUtils给全局安全工具类设置安全管理器
SecurityUtils.setSecurityManager(securityManager);
//4、关键对象 subject
Subject subject = SecurityUtils.getSubject();
//5、创建令牌
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","123");
// 身份认证
try {
System.out.println("认证状态:"+subject.isAuthenticated());
subject.login(token);
System.out.println("认证状态:"+subject.isAuthenticated());
}catch (UnknownAccountException e){
e.printStackTrace();
System.out.println("认证失败: 用户名不存在!");
}catch (IncorrectCredentialsException e){
e.printStackTrace();
System.out.println("认证失败:密码错误!");
}catch (Exception e){
e.printStackTrace();
}
}
}
4、读取数据库的Realm方式
4.1、CustomMd5Realm.java
package com.hello.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
/*
* 自定义realm: md5+salt盐值+hash散列
* */
public class CustomMd5Realm extends AuthorizingRealm{
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String primaryPrincipal = (String)principalCollection.getPrimaryPrincipal();
System.out.println("主身份信息:"+primaryPrincipal);
// 根据身份primaryPrincipal(用户名)信息,查询数据库中的角色信息以及权限信息
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRole("admin");
simpleAuthorizationInfo.addRole("user");
simpleAuthorizationInfo.addStringPermission("user:select:*");
simpleAuthorizationInfo.addStringPermission("product:delete:01");
return simpleAuthorizationInfo;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String principal = (String)authenticationToken.getPrincipal();
// 根据用户名查询数据库
if("zhangsan".equals(principal)){
// 匹配数据库的密文密码与用户输入的密码
return new SimpleAuthenticationInfo(principal, "2af4d9063ef264590d89b2a4fe430647", ByteSource.Util.bytes("!@#$%"), this.getName());
}
return null;
}
}
4.2、TestMd5Shiro.java
package com.hello;
import org.apache.shiro.crypto.hash.Md5Hash;
/*
* 根据 用户名+盐值+hash,用md5生成密文密码
* */
public class TestMd5Shiro {
public static void main(String[] args) {
Md5Hash md5Hash = new Md5Hash("123", "!@#$%", 3);
System.out.println(md5Hash.toHex());
}
}
4.3、TestCustomMd5RealmShiro.java
package com.hello.realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import java.util.Arrays;
public class TestCustomMd5RealmShiro {
public static void main(String[] args) {
System.out.println("================身份认证===========================");
// 创建默认的SecurityManager
DefaultSecurityManager securityManager = new DefaultSecurityManager();
// 创建自定义的Realm
CustomMd5Realm realm = new CustomMd5Realm();
// 设置realm使用hash凭证匹配器
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
matcher.setHashAlgorithmName("md5");
matcher.setHashIterations(3);
// 设置realm使用自定义的凭证匹配器
realm.setCredentialsMatcher(matcher);
// 给SecurityManager设置realm
securityManager.setRealm(realm);
// SecurityUtils工具类
SecurityUtils.setSecurityManager(securityManager);
// 获取主体
Subject subject = SecurityUtils.getSubject();
// 身份认证
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");
try {
subject.login(token);
System.out.println("认证状态:"+subject.isAuthenticated());
}catch (UnknownAccountException e){
e.printStackTrace();
System.out.println("认证失败: 用户名不存在!");
}catch (IncorrectCredentialsException e){
e.printStackTrace();
System.out.println("认证失败:密码错误!");
}catch (Exception e){
e.printStackTrace();
}
System.out.println("====================授权=======================");
if(subject.isAuthenticated()){
// 基于角色权限控制
System.out.println(subject.hasRole("admin"));
// 基于多角色的权限控制
System.out.println(subject.hasAllRoles(Arrays.asList("admin", "user")));
// 是否具有其中一个角色
boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "super", "user"));
for (boolean aBoolean : booleans) {
System.out.println(aBoolean);
}
System.out.println("==========================");
// 基于权限字符串的访问控制, 资源标识符:操作:资源类型
System.out.println("权限:"+subject.isPermitted("user:select:01"));
System.out.println("权限:"+subject.isPermitted("product:delete"));
// 分别具有哪些权限
boolean[] permitted = subject.isPermitted("user:select", "user:delete", "product:delete");
for (boolean b : permitted) {
System.out.println("权限:"+ b);
}
// 同时具有哪些权限
boolean permittedAll = subject.isPermittedAll("user:select", "user:delete", "product:delete");
System.out.println("权限:"+permittedAll);
}
}
}