一、Shiro的快速开始
1.Shiro的简单介绍
Shiro的官方介绍文档:
http://shiro.apache.org/
2.快速开始
shiro在github上有官方的快速开始文档:
https://github.com/apache/shiro
该目录下便是Shiro的快速开始示例;我们依据他官方的快速示例进行配置。
(1)首先引入我们Shiro的依赖包:
<!-- shiro 依赖 start-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency> <!-- configure logging -->
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- shiro 依赖 end-->
(2)而后将里面的shiro.ini文件拷贝到resources下:
此代码拷贝过来后会提示下载关于ini的插件,需要下载一下,便于阅读ini类型的文件
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
(3)快速开始我们的shiro类:Quickstart.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.lang.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
currentUser.logout();
System.exit(0);
}
}
此时我们项目中已经可以测试使用Shiro了。但是在实际项目中还是要对Shiro进行配置的。
二、Shiro的配置使用
1.Spring boot整合Shiro环境搭建
(1)先引入Shiro整合spring的依赖包
<!-- shiro整合spring依赖包 start-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
<!-- shiro整合spring依赖包 end-->
(2)而后我们先新建几个页面:index.html(主页面),add.html,update.html后续我们将通过这三个页面来对我们的Shiro进行测试。这三个页面全部放置在templates下的user(需要自己新建)文件夹下即可:
前端页面中会用到thymeleaf语法,我们先导入thymeleaf的依赖包:
<!-- thymeleaf模板 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
index.html:
<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<!-- 从session中判断值 -->
<div>
<a th:href="@{/toLogin}">登录</a>
</div>
<p th:text="${msg}"></p>
<hr>
<a href="@{/user/add}">add</a> | <a href="@{/user/update}">update</a>
</body>
</html>
add.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Add</h1>
</body>
</html>
update.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
(3)添加ShiroController用于在这三个页面之间进行跳转
@Controller
public class ShiroController {
@RequestMapping("/shiro")
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "user/index";
}
@RequestMapping("user/add")
public String add(){
return "user/add";
}
@RequestMapping("user/update")
public String update(){
return "user/update";
}
}
此时便可以通过index页面跳转到add和update页面。
2.对Shiro进行配置
新建ShiroConfig配置类
对Shiro的配置,主要由这三步构成:
第一步:创建realm对象
新建UserRealm类:
//自定义的UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了=》授权doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=》认证doGetAuthorizationInfo");
return null;
}
}
在ShiroConfig进行第一步的配置:创建realm对象
第二步:DefaultWebSecurityManager
第三步:ShiroFilterFactoryBean
ShiroConfig中,一个方法套一个方法,关联性很强。
3.Shiro实现登录拦截
在ShiroConfig的第三步中添加过滤器:
此时再次启动项目进入index页面向add和update页面跳转便会报404错误,因为此时还没有进行认证。
为了让他跳转失败之后,自动跳转到登录页面,我们还需要在user文件夹下添加一个登录页面login.html:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<hr>
<p th:text="${msg}" style = "color:red;"></p>
<form th:action="@{/login}">
<p>用户名:<input type="text" name="username"></p>
<p>密码:<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
还需要再在ShiroController中添加跳转到登录页面的业务:
@RequestMapping("toLogin")
public String toLogin(){
return "user/login";
}
然后再在ShiroConfig的第三步中设置跳转到登录页面:
此时在index页面中点击add和update时,便会跳转到登录页面。
4.Shiro实现用户的认证
(1)在ShiroController类中添加登录业务
@RequestMapping("login")
public String login(String username,String password,Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try{
subject.login(token); //执行登录的方法,如果没有异常,说明OK
return "user/index";
}catch(UnknownAccountException e){ //用户名不存在
model.addAttribute("msg","用户名错误!");
return "user/login";
} catch (IncorrectCredentialsException e) { //密码不正确
model.addAttribute("msg", "密码错误!");
return "user/login";
}
}
(2)修改登录页面的表单请求,并添加一个展示上面的提示信息的内容:
Shiro的ShiroConfig类和UserRealm类这两个类有着内在的联动,此时我们进入登录页面输入用户名和密码点击登录,会进入到UserRealm类中的认证方法中。此时我们便可以在这个认证方法中对用户进行以一系列的认证操作。
UserRealm类中的认证方法:
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=》认证doGetAuthorizationInfo");
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的的登录数据
//用户名,密码,应该数据库中取,这边测试没有连接数据库,所以直接赋值
String name = "root";
String password = "123456";
UsernamePasswordToken userToken =(UsernamePasswordToken) token;
if(!userToken.getUsername().equals(name)){
return null; //抛出异常 UnknownAccountException
}
//密码认证,shiro做,不需要我们自己getPassword
return new SimpleAuthenticationInfo("",password,"");
}
此时,我们只有使用:用户名:root ,密码:123456,才能登录成功,并且能够跳转到add和update页面。
5.Shiro实现用户的授权
用户的授权首先先进入ShiroConfig类中的第三步(ShiroFilterFactoryBean)中,可以设置授权过滤,没有授权的会跳转到未授权页面。
在ShiroController类中添加未授权业务:
@RequestMapping("/noauth")
@ResponseBody //返回字符串
public String unauthorized(){
return "未经授权无法访问此页面";
}
此时登录root,123456用户,只可以登录成功index页面,不能够访问add和update页面,因为此时该用户还没有访问这两个页面的权限。
现在我们要为用户进行授权,我们开始修改UserRealm类中的授权方法,这个授权方法,当用户登录成功后,比如点击add想要跳转到add.html页面时,便会执行该UserRealm类的授权方法。
上面代码中,没连接数据库时为用户进行授权是一个死代码,仅为测试使用,因为此时无论什么用户,这要登录成功了,点击add想要跳转到add.html页面,该代码都会给当前登录用户授权。所以要连接数据库才能实现不同用户,拥有不同的权限。
UserRealm类中的授权方法:
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了=》授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add"); //对这一句filterMap.put("/user/add","perms[user:add]");进行授权
//拿到当前登录的这个对象(连接数据库后的操作)
//Subject subject = SecurityUtils.getSubject();
//User currentUser = (User)subject.getPrincipal(); //拿到user对象
//info.addStringPermission(currentUser.getPerms()); //未用户设置权限,perms是数据库中用户的权限
return info;
}
6.Shiro整合Thymeleaf
还有最后一步,就是前端页面的展示,我们希望当不同的用户登录时,index页面只显示该用户拥有权限的那一部分,比如root用户登录,此时root用户只有访问add.html页面的权限,而没有访问update.html页面的权限,此时我们希望当root用户登录index页面时,只给root用户展示add的跳转链接,而不展示update的跳转链接。这就需要我们的Shiro整合Thymeleaf进行使用了。
(1)引入Shiro整合Thymeleaf的依赖包
<!-- Shiro-thymeleaf整合 start 需要配置 在ShiroConfig中进行了配置-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Shiro-thymeleaf整合 end-->
(2)ShiroConfig中进行配置
//整合ShiroDialect:用来整合shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
(3)对index.html页面进行修改
修改后的index.html页面:
<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<!-- 从session中判断值 -->
<div th:if(session)>
<a th:href="@{/toLogin}">登录</a>
</div>
<p th:text="${msg}"></p>
<hr>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>
</body>
</html>
至此,我们便可以根据不同用户的登录,拥有的权限不一致,进行区别展示。
同时我们也学习完成了对Shiro的简单使用。(我这边没有进行讲解Shiro整合Mybatis的部分,是因为Mybatis是关于数据库的部分,应该是一个单独的模块,我们只需学习Mybatis的使用,便可以在Shiro中进行使用)