介绍
1、Apache Shiro 是 Java 的一个安全框架。目前,使用 Apache Shiro 的人越来越多,因为它相当简单,对比 Spring Security,可能没有 Spring Security 做的功能强大,但是在实际工作时可能并不需要那么复杂的东西,所以使用小而简单的 Shiro 就足够了。
2、Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境,也可以用在 JavaEE 环境。Shiro 可以帮助我们完成:认证、授权、加密、会话管理、与 Web 集成、缓存等
Authentication:身份认证 / 登录,验证用户是不是拥有相应的身份;
Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
Session Management:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通 JavaSE 环境的,也可以是如 Web 环境的;
Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
Caching:缓存,比如用户登录后,其用户信息、拥有的角色 / 权限不必每次去查,这样可以提高效率;
Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。
这里使用代码介绍
我们需要进行配置shiro的配置文件shiro.ini,shiro可以读取到ini中的加密方式,用户-密码,以及权限。(之后可以使用数据库替代)
1、shiro.ini
#指定主配置
[main]
#配置加密方法路径,以及加密次数
#md5CredentialsMatcher表示一个变量名,存储加密方式md5家吗
md5CredentialsMatcher=org.apache.shiro.authc.credential.Md5CredentialsMatcher
#hashIterations=2表示进行两次加密
md5CredentialsMatcher.hashIterations=2
#com.sc.shiro01.realm.MyRealm表示的是一个验证类
myrealm=com.sc.shiro01.realm.MyRealm
#将md5验证放入myrealm中
myrealm.credentialsMatcher=$md5CredentialsMatcher
#安全管理的验证域为MyRealm
securityManager.realms=$myrealm
#users指明用户,密码以及权限
[users]
#用户名=密码,角色1,角色2.....
zhangsan=zs,role1,role2
lisi=ls
#定义角色对应的权限
[roles]
#角色名=权限1,权限2,.....
role1=sys:user:insert,sys:user:delete
role2=delete,update
2、配置文件引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- 配置外部依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>compile</scope>
</dependency>
<!-- 配置shiro自己的依赖,直接使用shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
3、验证域MRealm.java
package com.sc.shiro01.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.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
/**
* 自定义的realm类,在该类中可以声明自定义的登录认证和授权的方法
* 当程序写了自定义的realm后,通过ini中设置的main读取到自定义的realm,
* 不在需要进行在ini中进行比较user
*/
public class MyRealm extends AuthenticatingRealm {
// 自定义的登录认证方法
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 获取用户的登录身份,唯一的
String username = token.getPrincipal().toString();
// 获取用的登录凭证
String pwd = token.getCredentials().toString();
System.out.println(username+" ---> "+pwd);
if(username.equals("admin")){
String sysPwd = "b106dc6352e5ec1f8aafd8c406d34d92"; // 加密两次的密文
// SimpleAuthenticationInfo中第三个参数为加密的盐,该盐需要为byte类型。
// 第四个参数为域名
AuthenticationInfo authenticationInfo =
new SimpleAuthenticationInfo(token.getPrincipal(),
sysPwd, ByteSource.Util.bytes("abc"),token.getPrincipal().toString());
return authenticationInfo;
}
return null;
}
}
4、调用方法
package com.sc.shiro01.Control;
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;
import org.junit.jupiter.api.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/")
public class TestShiro {
@RequestMapping("login2")
@ResponseBody // 使用这个可以返回普通字符串
public String login2(String account,String pwd){
// 获取SecurityManager对象
IniSecurityManagerFactory factory =
new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// 得到当前Subject对象
Subject subject = SecurityUtils.getSubject();
// 把账号密码封装为token令牌
AuthenticationToken token =
new UsernamePasswordToken(account,pwd);
try{
// 当主角执行登录操作
subject.login(token);
boolean role1 = subject.hasRole("role1");
System.out.println("判断是否具有该角色:" + role1);
subject.checkPermission("sys:user:insert"); // 查看报错能知道有没有返回值。
boolean isbooean = subject.isPermitted("sys:user:insert"); //判断是否有权限会有返回值
System.out.println("是否具有权限:" + isbooean);
System.out.println("登录成功");
return "登录成功";
}catch (UnknownAccountException e){
System.out.println("账号不存在");
return "账号不存在";
}catch (IncorrectCredentialsException e){
System.out.println("密码错误");
return "密码错误";
}catch (Exception e){
System.out.println("权限不足");
return "权限不足";
}
}
}
5、关于shiro中的加密方法设置,(这里没有将加密方法写入到项目中):
package com.sc.shiro01;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.junit.jupiter.api.Test;
public class TestMD5 {
@Test
public void testMD(){
String password = "123";
Md5Hash md5Hash = new Md5Hash(password);
System.out.println("一次加密的结果:" + md5Hash);
// 进行带盐加密
Md5Hash md5Hash1 = new Md5Hash(password,"abc"); // 进行加盐处理
System.out.println("进行加盐处理:" + md5Hash1);
// 加盐并两次加密
Md5Hash md5Hash2 = new Md5Hash(password,"abc",2); // 2次加密
System.out.println("加盐并且进行两次加密:" + md5Hash2);
}
}