Shiro三大对象Subject,SecurityManger,Realm依次是用户,管理所有用户,连接数据
快速开始
导入依赖
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<!-- Shiro uses SLF4J for logging. We'll use the 'simple' binding
in this example app. See http://www.slf4j.org for more info. -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
shiro配置文件 shiro.ini
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[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
log4j配置文件
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
Hello World
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
//import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
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;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Tutorial {
private static final transient Logger log = LoggerFactory.getLogger(Tutorial.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();
//新方法 shiro更新问题
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);
}
}
从快速开始可以发现几个方法
Subject currentUser = SecurityUtils.getSubject(); //获取subject
Session session = currentUser.getSession(); //获取session
session.setAttribute("someKey", "aValue"); // 存值取值
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
springBoot 整和 shiro
步骤 导入依赖 编写配置类
依赖
<!-- shiro-spring整合-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
登录拦截 用户拦截 未连接数据库
@Configuration
public class ShiroConfiger {
//Realm
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
// @Qualifier("userRealm") 和上方的Realm绑定
@Bean(name = "securityManager" )
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
//关联Realm
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(userRealm);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager ){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//关联 安全管理器
factoryBean.setSecurityManager(defaultWebSecurityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//设置等级
filterChainDefinitionMap.put("/add","authc");
filterChainDefinitionMap.put("/update","authc");
factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
//设置登录的请求
factoryBean.setLoginUrl("/toLogin");
return factoryBean;
}
}
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行授权");
return null;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行认证");
String name="admin";
String password="123";
// 此token 是接收了前端传回来的数据并处理后的,及login请求里的token
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
System.out.println(userToken.getUsername());
if (!userToken.getUsername().equals(name)){
return null; //抛出异常 UnknownAccountException
}
// //密码认证,shiro做
return new SimpleAuthenticationInfo("",password,"");
}
}
@Controller
public class indexController {
@GetMapping({"/index.html","/"})
public String index(){
return "index";
}
@GetMapping({"/add"})
public String add(){
return "add";
}
@GetMapping({"/update"})
public String update(){
return "update";
}
@GetMapping("/toLogin")
public String toLogin(){
return "login";
}
@PostMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据 令牌
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try{
subject.login(token); //执行登录方法,如果没有异常就ok
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<a href="/add">add</a> |
<a href="/update">update</a>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<form action="/login" method="post">
<p style="color: red" th:text="${msg}"></p>
<p>用户名<input type="text" name="username"></p>
<p>密码<input type="password" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
add update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
连接数据库
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
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 javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfiger {
//Realm
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
// @Qualifier("userRealm") 和上方的Realm绑定
@Bean(name = "securityManager" )
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
//关联Realm
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(userRealm);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager ){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//关联 安全管理器
factoryBean.setSecurityManager(defaultWebSecurityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//设置等级
/*
anon 无拦截
authc 认证后登录
user 拥有记住我访问
perms 拥有某个资源权限权限
role 拥有某个角色权限权限
*/
filterChainDefinitionMap.put("/add","perms[user:add]"); //设置权限 user:add
filterChainDefinitionMap.put("/update","authc");
factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
//设置登录的请求
factoryBean.setLoginUrl("/toLogin");
//设置无权限的请求
factoryBean.setUnauthorizedUrl("/unauth");
return factoryBean;
}
}
import com.example.pojo.User;
import com.example.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
public class UserRealm extends AuthorizingRealm {
// 掉service连接数据库
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行授权");
//获取用户
Subject subject = SecurityUtils.getSubject();
// 获取认证时传递的资源 及第一个参数 user
User principal = (User) subject.getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 将数据库中的权限列表 添加到 用户上
info.addStringPermission(principal.getParm());
// SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //两种都行
// User primaryPrincipal = (User) principalCollection.getPrimaryPrincipal();
// String parm = primaryPrincipal.getParm();
// info.addStringPermission(parm);
return info;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行认证");
//从前端传来,过/login 请求下 token 同一个token
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实数据库
User user = userService.queryByName(userToken.getUsername());
if (user==null){
return null; //UnknownAccountException
}
//密码认证,shiro做 可以添加密码加密 认证后授权,可以在认证的时候传递资源到授权及user
return new SimpleAuthenticationInfo(user,user.getUserPwd(),"");
}
}
import com.sun.org.apache.xpath.internal.operations.Mod;
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.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class indexController {
@GetMapping({"/index.html","/"})
public String index(){
return "index";
}
@GetMapping({"/add"})
public String add(){
return "add";
}
@GetMapping({"/update"})
public String update(){
return "update";
}
@GetMapping("/toLogin")
public String toLogin(){
return "login";
}
@PostMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
// 加密
// password = DigestUtils.md5DigestAsHex(password.getBytes());
//封装用户的登录数据 令牌
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try{
subject.login(token); //执行登录方法,如果没有异常就ok
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
//未授权的页面
@ResponseBody
@GetMapping("/unauth")
public String unauthorized(){
return "未找到访问该页面的权限";
}
@GetMapping("/logout")
public String logout(){
SecurityUtils.getSubject().logout();
return "index";
}
}
import com.example.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {
public User queryByName(String username);
}
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.example.mapper.UserMapper">
<select id="queryByName" resultType="com.example.pojo.User">
select * from user where userCode=#{userName}
</select>
</mapper>
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String userCode;
private String userName;
private String userPwd;
private String parm;
}
public interface UserService {
public User queryByName(String username);
}
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryByName(String username) {
return userMapper.queryByName(username);
}
}
yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3366/buybooks
username: root
password: 123456
druid:
aop-patterns: com.atguigu.admin.* #监控SpringBean
filters: stat,wall # 底层开启功能,stat(sql监控),wall(防火墙)
# 配置监控页功能
stat-view-servlet:
enabled: true
login-username: admin
login-password: 123
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
filter:
stat: # 对上面filters里面的stat的详细配置
slow-sql-millis: 1000
logSlowSql: true
enabled: true
wall:
enabled: true
config:
drop-table-allow: false
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true #带有下划线的表字段映射为驼峰格式的实体类属性。
type-aliases-package: com.example.pojo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<a href="/add">add</a> |
<a href="/update">update</a>
<a href="/logout">logout</a>
</body>
</html>
shiro和thymeleaf整合
改过的如下,建议从头开始
<!-- shiro-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>
@Configuration
public class ShiroConfiger {
//Realm
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
// @Qualifier("userRealm") 和上方的Realm绑定
@Bean(name = "securityManager" )
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
//关联Realm
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(userRealm);
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager ){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//关联 安全管理器
factoryBean.setSecurityManager(defaultWebSecurityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//设置等级
/*
anon 无拦截
authc 认证后登录
user 拥有记住我访问
perms 拥有某个资源权限权限
role 拥有某个角色权限权限
*/
filterChainDefinitionMap.put("/add","perms[user:add]"); //设置权限 user:add
filterChainDefinitionMap.put("/update","authc");
factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
//设置登录的请求
factoryBean.setLoginUrl("/toLogin");
//设置无权限的请求
factoryBean.setUnauthorizedUrl("/unauth");
return factoryBean;
}
// ShiroDialect 用来整合 shiro-thymeleaf整合
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<div shiro:hasPermission="user:add">
<a href="/add">add</a> |
</div>
<a th:href="@{/toLogin}">toLogin</a>
<a href="/update">update</a>
<a href="/logout">logout</a>
</body>
</html>