认识shiro
什么是shiro?
Apache shiro 是一个java的安全(权限)框架
shiro可以非常容易的开发出足够好的应用,不仅可以在javaSE,还可以在javaEE环境
作用:可以完成认证 ,授权, 加密,会话管理,web集成,缓存
下载地址:http://shiro.apache.org
您可以使用Apache Shiro进行以下操作:
验证用户身份以验证其身份
对用户执行访问控制,例如:
**确定是否为用户分配了特定的安全角色
**确定是否允许用户做某事
即使在没有Web或EJB容器的情况下,也可以在任何环境中使用Session API。
在身份验证,访问控制或会话的生存期内对事件做出反应。
汇总1个或更多用户安全数据的数据源,并将其全部显示为单个复合用户“视图”。
启用单点登录(SSO)功能
启用“记住我”服务以进行用户关联,而无需登录
…
等等-所有这些都集成到一个紧密结合的易于使用的API中。
Shiro尝试在所有应用程序环境中实现这些目标-从最简单的命令行应用程序到最大的企业应用程序,而不必强加对其他第三者框架,容器或应用程序服务器的依赖。当然,该项目旨在尽可能地将其集成到这些环境中,但是它可以在任何环境中直接使用。
Apache shiro的功能
身份验证:有时称为“登录”,这是证明用户就是他们所说的身份的行为。
授权:访问控制的过程,即确定“谁”有权访问“什么”。
会话管理:即使在非Web或EJB应用程序中,也可以管理用户特定的会话。
密码术:使用密码算法保持数据安全,同时仍然易于使用
shiro架构
您的第一个Apache Shiro应用程序
准备工作:
建立maven项目:
1.在pom.xml中导入依赖
2.创建shiro.ini文件
3.创建Quickstart文件
4.创建log4j.properties
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.5.1</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</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>
[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
/*
* 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.
*/
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.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.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 Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//获取当前的用户对象:
Subject currentUser = SecurityUtils.getSubject();
// 通过当前的用户拿到session值
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 + "]");
}
// 判断当前用户是否被认证
if (!currentUser.isAuthenticated()) {
//token 令牌
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!");
}
//注销
currentUser.logout();
//结束
System.exit(0);
}
}
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
最后运行Quickstart文件
Quickstart文件中:掌握具体的方法是用来干什么的
springboot整合shiro环境搭建
1.添加spring-shiro整合依赖包
<dependency>
<!-- shiro核心有三大对象
1.Subject 用户
2.securityManager 管理所有用户
3.Realm 连接数据源
shiro-spring-->
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.1</version>
</dependency>
- 自定义realm 需要继承AuthorizingRealm 类
//自定义的UserRealm 需要继承 AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权 doGetAuthorizationInfo ");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证 doGetAuthenticationInfo");
return null;
}
}
3.shiro环境配置
package wu.config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean(第三步)
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//关联第二步的manager
factoryBean.setSecurityManager(getDefaultWebSecurityManager());
return factoryBean;
}
//DefaultWebSecurityManager(第二步)
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(){
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
//关联第一步的realm
securityManager.setRealm(userRealm());
return securityManager;
}
//Realm 创建realm对象 需要自定义(第一步)
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
环境搭建成功
shiro实现登录拦截
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean(第三步)
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//关联第二步的manager
factoryBean.setSecurityManager(getDefaultWebSecurityManager());
//添加shiro的内置过滤器
/*
* anon 无需认证即可访问
* authc 必须认证才能访问
* User 必须拥有 记住我 功能才能访问
*perms 拥有对某一个资源的权限才能访问
*role 拥有某一个角色权限才能访问
* */
//登录拦截
Map<String, String> filterMap =new LinkedHashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
filterMap.put("/user/*","authc");
factoryBean.setFilterChainDefinitionMap(filterMap);
//设置登录请求
factoryBean.setLoginUrl("/toLogin");
return factoryBean;
}
//DefaultWebSecurityManager(第二步)
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(){
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
//关联第一步的realm
securityManager.setRealm(userRealm());
return securityManager;
}
//Realm 创建realm对象 需要自定义(第一步)
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
添加测试页面:登录页面,添加用户页面,更新用户页面
shiro实现认证
对于shiro来说,一般是先执行认证后执行授权
shiro认证:
1.添加依赖:
mysql驱动,druid数据源,thymeleaf,web,shiro-spring,mybatis-springboot
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<!-- shiro-spring-->
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.1</version>
</dependency>
<!-- druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<!-- mybatis-springboot-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<!-- mysql驱动-->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
<scope>runtime</scope>
</dependency>
2.配置yml相关属性以及数据库连接
spring:
thymeleaf:
cache: false
#数据连接
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
# 调用type 使用数据连接池
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
type-aliases-package: wu.pojo
mapper-locations: classpath:mapper/*.xml
3.创建mvc相关目录
pojo,mapper,service,controller,等等
4.用户认证
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
System.out.println("认证 doGetAuthenticationInfo");
//伪造数据
/*String username="admin";
String password="123456";
UsernamePasswordToken userToken=(UsernamePasswordToken)Token;
if (!userToken.getUsername().equals(username)){
return null;//会自动抛出异常
}
//密码认证 自动
return new SimpleAuthenticationInfo("",password,"");*/
//数据库获取数据
UsernamePasswordToken userToken=(UsernamePasswordToken)Token;
User user = userService.queryByName(userToken.getUsername());
if (user==null){
return null;
}//密码可以采用MD5加密或者MD5盐值加密
return new SimpleAuthenticationInfo("",user.getPassword(),"");
}
效果:只有数据库表格中的用户才能访问
shiro实现授权
/*
* anon 无需认证即可访问
* authc 必须认证才能访问
* User 必须拥有 记住我 功能才能访问
*perms 拥有对某一个资源的权限才能访问
*role 拥有某一个角色权限才能访问
* */
在拦截地方进行授权管理:
* */
//登录拦截
Map<String, String> filterMap =new LinkedHashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
//filterMap.put("/user/*","authc");
//授权
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
factoryBean.setFilterChainDefinitionMap(filterMap);
//设置登录请求
factoryBean.setLoginUrl("/toLogin");
//未授权页面
factoryBean.setUnauthorizedUrl("/Unauthor");
return factoryBean;
}
如果未授权进入授权页面
注销用户可以使用shiro自带方法logout()
@RequestMapping("/logout")
public String logout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/toLogin";
}
}