Shiro
Apache Shiro 是 Java 的一个安全框架。
Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境,也可以用在 JavaEE 环境。Shiro 可以帮助我们完成:认证、授权、加密、会话管理、与 Web 集成、缓存等。
Subject 代表当前用户,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是 Subject
SecurityManager 安全管理器 管理所有用户
Realm 可以把 Realm 看成 DataSource,即安全数据源。
简单步骤
应用代码通过 Subject 来进行认证和授权,而 Subject 又委托给 SecurityManager;
我们需要给 Shiro 的 SecurityManager 注入 Realm,从而让 SecurityManager 能得到合法的用户及其权限进行判断
QuickStart
- 导入依赖
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.1</version>
</dependency>
<!-- configure logging -->
<!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
- 配置文件
log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
shiro.ini(idea 需添加相应插件)
[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
- QuickStart.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.util.Factory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
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();
DefaultSecurityManager securityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
securityManager.setRealm(iniRealm);
// 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);
}
}
SpringBoot整合Shiro 环境搭建
编写Shiro的Config类
package com.example.demo.Config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//4.创建ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager Manager){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//5.关联SecurityManager
factoryBean.setSecurityManager(Manager);
return factoryBean;
}
//2.创建DefaultWebSecurityManager
@Bean(name = "SecurityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager( UserRealm userRealm){
DefaultWebSecurityManager SecurityManager=new DefaultWebSecurityManager();
//3.关联Realm
SecurityManager.setRealm(userRealm);
return SecurityManager;
}
//1.创建Realm对象
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
public class UserRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("授权----------->");
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证------------");
return null;
}
}
登录拦截
目标:使未登录的用户不能直接访问页面 在搭好环境之后,我们只需在 shiroFilterFactoryBean中进行配置即可 首先我们通过Map来存放我们的条件
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager Manager){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//5.关联SecurityManager
factoryBean.setSecurityManager(Manager);
/*
anon 无需授权、登录就可以访问,所有人可访。
authc 需要登录授权才能访问。
authcBasic Basic HTTP身份验证拦截器
logout 退出拦截器。退出成功后,会 redirect到设置的/URI
noSessionCreation 不创建会话连接器
perms 授权拦截器,拥有对某个资源的权限才可访问
port 端口拦截器
rest rest风格拦截器
roles 角色拦截器,拥有某个角色的权限才可访问
ssl ssl拦截器。通过https协议才能通过
user 用户拦截器,需要有remember me功能方可使用
*/
Map<String,String> filterMap = new LinkedHashMap<>();
//对/user/*下的文件只有拥有authc权限的才能访问
filterMap.put("/user/*","authc");
//将Map存放到ShiroFilterFactoryBean中
factoryBean.setFilterChainDefinitionMap(filterMap);
//需进行权限认证时跳转到toLogin
factoryBean.setLoginUrl("/toLogin");
//权限认证失败时跳转到unauthorized
factoryBean.setUnauthorizedUrl("/unauthorized");
return factoryBean;
}
用户认证
目标:对用户的登录进行判断 1.首先我们建立一个login.html页面,有一个简单的form表单提交到/login
<form action="/login">
<span style="color:red" th:text="${msg}"></span><br>
用户名<input type="text" name="username"><br>
密码<input type="password" name="password"><br>
<input type="submit">
</form>
2.我们在Controller中配置相应的处理
//设置路径为/login,即让表单提交到这里
@RequestMapping("/login")
public String login(String username,String password,Model model){
//获取当前用户
Subject s= SecurityUtils.getSubject();
//根据用户名密码获取对应的token
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
try{
//用户登录
s.login(usernamePasswordToken);
//成功就跳到首页
return "index";
}//没有这个用户
catch (UnknownAccountException uae){
model.addAttribute("msg","username error");
//返回登录页
return "login";
}//密码错误
catch (IncorrectCredentialsException ice){
model.addAttribute("msg","password error");
//返回登录页
return "login";
}
}
3.当我们调用login方法时就会进入到Realm的doGetAuthenticationInfo
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证------------");
//将参数token转换为其子类的UsernamePasswordToken
UsernamePasswordToken u=(UsernamePasswordToken)token;
//通过Username获取到数据库中的对象
User userByName = userController.getUserByName(u.getUsername());
//对象不存在
if (userByName==null)
return null;
//密码认证
return new SimpleAuthenticationInfo("",userByName.getPwd(),"");
}
授权
目标:使特定用户只能访问特定页面
- 在ShiroConfig中我们只需添加以下两行代码即可开启拦截
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
现在只有 拥有对应权限的用户可访问这两个页面
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager Manager){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//5.关联SecurityManager
factoryBean.setSecurityManager(Manager);
Map<String,String> filterMap = new LinkedHashMap<>();
//先授权再认证,如果将认证写在授权前面,一旦拦截判断成功就不再对之后的进行判断
//即先认证再授权,认证之后不再进行授权
// perms 授权拦截器,拥有对某个资源的权限才可访问
//对于add只有拥有user:add权限的人才可以访问,对update同理
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
factoryBean.setFilterChainDefinitionMap(filterMap);
//需进行权限认证时跳转到toLogin
factoryBean.setLoginUrl("/toLogin");
//权限认证失败时跳转到unauthorized
factoryBean.setUnauthorizedUrl("/unauthorized");
return factoryBean;
}
-
在UserRealm中的doGetAuthorizationInfo(获取授权信息)中根据数据库中的perm对每个用户进行授权
-
首先我们在doGetAuthenticationInfo返回的对象中传入当前用户
new SimpleAuthenticationInfo(userByName,userByName.getPwd(),"");
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证------------");
UsernamePasswordToken u=(UsernamePasswordToken)token;
User userByName = userController.getUserByName(u.getUsername());
if (userByName==null)
return null;
//密码认证 shiro自动做
return new SimpleAuthenticationInfo(userByName,userByName.getPwd(),"");
}
- 在 doGetAuthorizationInfo获取并根据perm进行授权
@Autowired
UserController userController;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("授权----------->");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
User p =(User) principals.getPrimaryPrincipal();
info.addStringPermission(p.getPerm());
return info;
}
至此可为数据库中的用户设置相应的权限
整合thymeleaf
目标:当用户未登录时只看到登录按钮,登录后根据权限看到不同页面部分
导入依赖
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
在ShiroConfig中将ShiroDialect注入到ioc中
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
修改index页面
<!DOCTYPE html>
//使用shiro命名空间
<html lang="en"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/login" shiro:notAuthenticated>登录</a>
<div shiro:hasPermission="user:add">
<a href="/user/add">add</a>
</div>
<a shiro:hasPermission="user:update" href="/user/update">update</a>
</body>
</html>