shiro笔记+Shiro 整合Springboot 实现

这是我参与8月更文挑战的第22天,活动详情查看:8月更文挑战

shiro简介
什么是Shiro?
Apache Shiro 是一个Java 的安全(权限)框架
shiro 可以非常容易的开发出足够好的应用,其不仅可以用在Javase 环境,也可以用在Javaee环境
shiro 可以完成,认证,授权,加密,会话管理,Web 集成,缓存等。
在这里插入图片描述

  • ●Authentication:身份认证、登录,验证用户是不是拥有相应的身份;
  • ●Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限,即判断用户能否进行什么操
  • 作,如:验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否具有某个权限!
  • ●Session Manager:会话管理,即用户登录后就是第一次会话, 在没有退出之前,它的所有信息都在会话中;
  • 会话可以是普通的JavaSE环境,也可以是Web环境;
  • ●Cryptography:加密,保护数据的安全性,如密码加密存储到数据库中,而不是明文存储;
  • ●Web Support: Web支持, 可以非常容易的集成到Web环境;
  • ●Caching: 缓存,比如用户登录后,其用户信息,拥有的角色、权限不必每次去查,这样可以提高效率
  • ●Concurrency: Shiro支持多线程应用的并发验证,即,如在一 个线程中开启另一 一个线程,能把权限自动的传
  • 播过去
  • ●Testing: 提供测试支持;
  • ●Run As:允许-一个用户假装为另-一个用户(如果他们允许)的身份进行访问;
  • ●Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了
    在这里插入图片描述
  • ●Subject: 任何可以与应用交互的’用户’;
  • ●Security Manager:相当于SpringMVC中的DispatcherServlet; 是Shiro的心脏,所有具体的交互都通过
  • Security Manager进行控制,它管理者所有的Subject, 且负责进行认证,授权,会话,及缓存的管理。
  • ●Authenticator: 负责Subject认证,是一个扩展点,可以自定义实现;可以使用认证策略(Authentication
  • Strategy),即什么情况下算用户认证通过了;
  • ●Authorizer: 授权器,即访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中
  • 的那些功能;
  • ●Realm:可以有一个或者多个的realm, 可以认为是安全实体数据源,即用于获取安全实体的,可以用DBC实
  • 现,也可以是内存实现等等,由用户提供;所以一般在应用中都需要实现自己的realm
  • ●SessionManager: 管理Session生命周期的组件,而Shiro并不仅仅可以用在Web环境,也可以用在普通的
  • JavaSE环境中
  • ●Authorizer: 授权器,即访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中
  • 的那些功能; .
  • ●Realm: 可以有一一个或者多个的realm,可以认为是安全实体数据源,即用于获取安全实体的,可以用DBC实
  • 现,也可以是内存实现等等,由用户提供;所以-般在应用中都需要实现自己的realm
  • ●SessionManager: 管理Session生命周期的组件,而Shiro并不仅仅可以用在Web环境,也可以用在普通的
  • JavaSE环境中
  • CH用英J”,简筵:
  • ●CacheManager: 缓存控制器,来管理如用户,角色,权限等缓存的;因为这些数据基本上很少改变,放到缓
  • 存中后可以提高访问的性能;
  • ●Cryptography: 密码模块,Shiro提高了- -些常见的加密组件用于密码加密,解密等
  • 快速开始的第一个shiro*
  • pom .xml*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
xml复制代码<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>shiro</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>

<!-- https://mvnrepository. com/artifact/org. apache. shiro/shiro-core -->

<dependency>

<groupId>org.apache.shiro</groupId>

<artifactId>shiro-core</artifactId>

<version>1.4.1</version>

</dependency>

<!-- configure logging -->

<dependency>

<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>
<!--日志 start-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

</dependencies>


</project>

log4j.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
java复制代码#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
java复制代码#
# 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

官网复制就行哈
第一个demo 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
java复制代码/*
* 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.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.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做一些事情(不需要Web或EJB容器!!!)
Session session = currentUser.getSession();
// 设置session 会话
session.setAttribute("someKey", "aValue");
// 拿到对应的值
String value = (String) session.getAttribute("someKey");
// 判断
if (value.equals("aValue")) {
// 打印查看一下
System.out.println("value = " + value);
log.info("Retrieved the correct value! [" + value + "]");
}
//············································································以上是Subject 的工作
//让我们登录当前用户,以便我们可以检查角色和权限:
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 (AuthenticationException ae) {
//unexpected condition? error?
}
}
//说明他们是谁:
//打印其标识主体(在本例中为用户名):
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);
}
}

结果

1
2
3
4
5
6
7
8
9
10
java复制代码"C:\Program Files\Java\jdk1.8.0_231\bin\java.exe" "-javaagent:D:\idea\IntelliJ IDEA 2019.3.5\lib\idea_rt.jar=62162:D:\idea\IntelliJ IDEA 2019.3.5\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_231\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_231\jre\lib\rt.jar;E:\shiro\target\classes;E:\maven_jar包\org\apache\shiro\shiro-core\1.4.1\shiro-core-1.4.1.jar;E:\maven_jar包\org\apache\shiro\shiro-lang\1.4.1\shiro-lang-1.4.1.jar;E:\maven_jar包\org\apache\shiro\shiro-cache\1.4.1\shiro-cache-1.4.1.jar;E:\maven_jar包\org\apache\shiro\shiro-crypto-hash\1.4.1\shiro-crypto-hash-1.4.1.jar;E:\maven_jar包\org\apache\shiro\shiro-crypto-core\1.4.1\shiro-crypto-core-1.4.1.jar;E:\maven_jar包\org\apache\shiro\shiro-crypto-cipher\1.4.1\shiro-crypto-cipher-1.4.1.jar;E:\maven_jar包\org\apache\shiro\shiro-config-core\1.4.1\shiro-config-core-1.4.1.jar;E:\maven_jar包\org\apache\shiro\shiro-config-ogdl\1.4.1\shiro-config-ogdl-1.4.1.jar;E:\maven_jar包\commons-beanutils\commons-beanutils\1.9.3\commons-beanutils-1.9.3.jar;E:\maven_jar包\commons-collections\commons-collections\3.2.2\commons-collections-3.2.2.jar;E:\maven_jar包\org\apache\shiro\shiro-event\1.4.1\shiro-event-1.4.1.jar;E:\maven_jar包\org\slf4j\jcl-over-slf4j\1.7.21\jcl-over-slf4j-1.7.21.jar;E:\maven_jar包\org\slf4j\slf4j-api\1.7.21\slf4j-api-1.7.21.jar;E:\maven_jar包\org\slf4j\slf4j-log4j12\1.7.21\slf4j-log4j12-1.7.21.jar;E:\maven_jar包\log4j\log4j\1.2.17\log4j-1.2.17.jar" Quickstart
2020-12-23 20:09:50,625 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler...
value = aValue
2020-12-23 20:09:51,315 INFO [Quickstart] - Retrieved the correct value! [aValue]
2020-12-23 20:09:51,315 INFO [Quickstart] - User [lonestarr] logged in successfully.
2020-12-23 20:09:51,315 INFO [Quickstart] - May the Schwartz be with you!
2020-12-23 20:09:51,315 INFO [Quickstart] - You may use a lightsaber ring. Use it wisely.
2020-12-23 20:09:51,315 INFO [Quickstart] - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!

Process finished with exit code 0

分析一下源码
在这里插入图片描述
在这里插入图片描述
在那个inl 里解释了角色的指定
在这里插入图片描述
在这里插入图片描述
Springboot 跟Shiro 环境搭建
1,导入依赖

1
2
3
4
5
6
7
8
9
10
11
xml复制代码        <!--引入thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- shiro-spring 依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>

写config 类
在这里插入图片描述
Shior Config 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
java复制代码package com.jj.demo.config;

import org.apache.shiro.mgt.SecurityManager;
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;

@Configuration
public class ShiroConfig {
// shiro 的三个
// Subject 用户
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
return shiroFilterFactoryBean;

}
// SecurityManager 管理所有的用户
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
// 关联 Realm
defaultWebSecurityManager.setRealm(userRealm);
return defaultWebSecurityManager;
}

// Realm 连接数据
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}

Shiro 主要的三个
// Subject 用户
// SecurityManager 管理所有的用户

1
arduino复制代码// Realm 连接数据

写自己的Realm 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
java复制代码package com.jj.demo.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class UserRealm extends AuthorizingRealm {
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("principalCollection = 授权" + principalCollection);
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

System.out.println("authenticationToken = 认证" + authenticationToken);
return null;
}
}

简单的几个页面和控制层
在这里插入图片描述
控制层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
java复制代码package com.jj.demo.control;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Shirocontrol {
@RequestMapping({"/","/index"})
public String demo(Model model){
model.addAttribute("msg","你好啊,我的第一个Springboot-sgiro 程序!!");
return "index";
}
//跳转到添加
@RequestMapping("/user/add")
public String add(){
return "/user/add";
}
//跳转到更新
@RequestMapping("/user/update")
public String update(){
return "/user/update";
}
}

在这里插入图片描述
实现登录拦截功能!!
在这里插入图片描述
简单的写个登录的控制层,还有登录页面就可以了
效果
在这里插入图片描述
在这里插入图片描述
走到了我们指定的url
控制层写一个登录的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
java复制代码//    登录的
@RequestMapping("login")
public String login1(String name,String pwd,Model model){
// 获取当前的用户
Subject subject = SecurityUtils.getSubject();
// 封装当前登录的数据 获取到令牌
UsernamePasswordToken token = new UsernamePasswordToken(name,pwd);
try {
subject.login(token); //执行登录的方法,没有异常就跳出
return "index";
//
// 用户名不存在异常
} catch (UnknownAccountException uae) {
model.addAttribute("msg","用户名错!!");
return "login";
}

catch (IncorrectCredentialsException ice) {
model.addAttribute("msg","密码错误");
return "login";

}
}

会自动与我们写的UserRealm 的认证联系起来。效果

1
2
3
4
5
java复制代码2020-12-24 16:09:05.446  INFO 4028 --- [           main] com.jj.demo.DemoApplication              : Started DemoApplication in 1.929 seconds (JVM running for 3.107)
2020-12-24 16:09:16.455 INFO 4028 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-12-24 16:09:16.456 INFO 4028 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-12-24 16:09:16.458 INFO 4028 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
authenticationToken = 认证org.apache.shiro.authc.UsernamePasswordToken - 娇娇, rememberMe=false

连接数据库测试
实体类简单的几个name,pwd
在这里插入图片描述
简单的根据name 做个查询 具体代码非常简单。在UserRealm 上注入service 层即可!!

在自己写的UserRealm 类里认证里写上
pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
xml复制代码  <!--Lombok引入-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- shiro-spring 依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
<!-- log4-->
<!--日志 start-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- mysql 的-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis 的包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>

yml 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
yaml复制代码# 数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/op?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
druid:
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
#mybatis的配置
mybatis:
configuration:
# sql日志显示,这里使用标准显示
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 整合别名的包
# 数据库中如果有类似 如 user_name 等命名,会将 _后的字母大写,这里是为了和实体类对应
# map-underscore-to-camel-case: true
# 配置mapper文件的路径
type-aliases-package: com.jj.demo.pojo
mapper-locations: classpath:mapper/*.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
java复制代码//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

System.out.println("authenticationToken = 认证" + authenticationToken);

UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
vip vip = vipdaoserviceimpl.showbyname(userToken.getUsername());
if (vip.getName()==null){
return null;
//抛出异常
}
// 密码认证,shiro 来做

return new SimpleAuthenticationInfo("",vip.getPwd(),"");
}

授权功能!!
数据库添加字段
在这里插入图片描述
在 ShiroConfig 里加上如下代码
在这里插入图片描述
UserRealm类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
java复制代码//    授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("principalCollection = 授权" + principalCollection);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 添加方法
info.addStringPermission("vip:add");
info.addStringPermission("vip:update");
// 拿到当前登录的对象
Subject subject = SecurityUtils.getSubject();
// 拿到vip 对象
vip vip = (com.jj.demo.pojo.vip) subject.getPrincipal();
// 设置当前用户的权限
System.out.println("vip.getPerms() = " + vip.getPerms());
info.addStringPermission(vip.getPerms());
return info;
}

在这里插入图片描述

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%