目录
4.编写自定义config @EnableWebSecurity
一、SpringSecurity
在web的开发中,安全第一位!过滤器,拦截器
shiro,SpringSecurity两个
权限:
- 功能权限
- 访问权限
- 菜单权限
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
2.编写静态页面
3.编写工具类测试
package com.kun.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RouterController {
@RequestMapping({"/","index"})
public String index(){
return "index";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
4.编写自定义config @EnableWebSecurity
1.继承WebSecurityConfigurerAdapter
实现权限访问
@Override
protected void configure(HttpSecurity http) throws Exception {
// 首页所有人访问
http.authorizeHttpRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// 没有权限跳到登录页面 开启登录页面
http.formLogin();
// 防止网站工具
http.csrf().disable();
// 注销功能
http.logout().logoutSuccessUrl("/");
}
实现角色认证
// 认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("daiyu").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
.and()
.withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip3");
}
5.应有界面的显示与隐藏
1.导入依赖
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
2.导入命名空间(有提示)
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
<!--未登录-->
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>
</div>
<!-- 注销-->
<div sec:authorize="isAuthenticated()">
<a class="item">
用户名:<span sec:authentication="name"></span>
<!-- 还有就是这个改一下sec:authentication="principal.authorities"-->
角色:<span sec:authentication="principal.authorities"></span>
</a>
</div>
<div sec:authorize="isAuthenticated()">
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
</div>
<div class="column" sec:authorize="hasRole('vip1')">
6.开启记住我功能
http.rememberMe();
7.重命名
http.formLogin().loginPage("/toLogin") //登录界面
//当后台数据名字和前端的名字不匹配:这样改
.usernameParameter("username").passwordParameter("password")
.loginProcessingUrl("/login"); //命名完,可以直接在页面写这个名字
http.rememberMe().rememberMeParameter("remember");
//让按钮的name属性等于 它
二、shiro
hello shiro
1.导入依赖
<dependencies>
<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>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>runtime</scope>
</dependency>
2.配置文件
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
[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.快速开始
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
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) {
//原本的方法
// 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);
SecurityUtils.setSecurityManager(securityManager);
// get the currently executing user:
// 获取当前的用户对象
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("session==== [" + 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.");
//hasRole判断用户什么权限
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);
}
}
shiro整合spring
1.导入依赖
<!-- shiro - spring-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
2.创建一个类继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证");
return null;
}
}
3.测试
package com.kun.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.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiRoConfig {
//3
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("a") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(defaultWebSecurityManager);
/**
* 添加认证过滤器
* anon 无需认证
* authc 必须认证
* user 必须拥有记住我
* perms 拥有对某个资源的访问权限
* role 拥有对某个角色权限
*/
Map<String, String> map = new LinkedHashMap<>();
map.put("/user/add","authc");
bean.setFilterChainDefinitionMap(map);
bean.setLoginUrl("/toLogin");
return bean;
}
// 2
@Bean(name = "a")
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm());
return securityManager;
}
// 创建对象 1
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
shiro认证
@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);
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException i){
model.addAttribute("msg","密码错误");
return "login";
}
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证");
// 用户户名 密码
String name="root";
String password="123";
UsernamePasswordToken userToken= (UsernamePasswordToken) token;
if(!userToken.getUsername().equals(name)){
return null; //抛出异常
}
// 密码认证
return new SimpleAuthenticationInfo("",password,"");
}
shiro整合mybatis
导入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
编写配置文件
spring:
datasource:
username: root
password: root
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
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=com.kun.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
pojo实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
mapper接口UserMapper
@Repository
@Mapper
public interface UserMapper {
List<User> queryUserList();
User queryUser(String name);
}
mapper接口映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kun.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from mybatis.user;
</select>
<select id="queryUser" resultType="User" parameterType="String">
select *
from mybatis.user where name=#{name};
</select>
</mapper>
编写事务层 UserService接口
public interface UserService {
List<User> queryUserList();
User queryUser(String name);
}
编写事务层 UserService接口实现类
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public List<User> queryUserList() {
return userMapper.queryUserList();
}
@Override
public User queryUser(String name) {
return userMapper.queryUser(name);
}
}
实现测试
public class UserRealm extends AuthorizingRealm {
@Autowired
UserServiceImpl userService;
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证");
// 用户户名 密码
// String name="root";
// String password="123";
UsernamePasswordToken userToken= (UsernamePasswordToken) token;
// 连接真实数据库
User user = userService.queryUser(userToken.getUsername());
if (user==null){
return null;
}
// 可以密码加密 md5加密 MD5盐值加密
// 密码认证
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}
/**
* 添加认证过滤器
* anon 无需认证
* authc 必须认证
* user 必须拥有记住我
* perms 拥有对某个资源的访问权限
* role 拥有对某个角色权限
*/
Map<String, String> map = new LinkedHashMap<>();
map.put("/user/add","authc");
bean.setFilterChainDefinitionMap(map);
map.put("/user/add","perms[李明]"); //李明用户
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addStringPermission("user:add");
// 拿到当前用户对象
Subject subject = SecurityUtils.getSubject();
User principal = (User) subject.getPrincipal(); //拿到对象
System.out.println(principal.getName());
info.addStringPermission(principal.getName());
return info;
}
整合thymeleaf
导入依赖
<!-- shiro-thymeleaf整合-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
配置
// 整合shirodialect
@Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
测试
<div shiro:hasPermission="李明">
<h1>add</h1>
</div>
错误:
错误一: 认证完,登录时,报500错误,密码编码错误(密码没有加密)
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("daiyu").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
错误二:
用户名:<span sec:authentication="name"></span>
<!--还有就是这个改一下sec:authentication="principal.authorities"->
principal.getAuthorities()
角色:<span sec:authentication="principal.authorities"></span>
shiro错误三:
java.lang.NoClassDefFoundError: org/apache/log4j/Level架包冲突,删除相应的架包即可
错误四:
import org.apache.shiro.ini.IniSecurityManagerFactory出错;
报Cannot resolve symbol ‘ini‘等错误;
过时问题:
DefaultSecurityManager securityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
securityManager.setRealm(iniRealm);
SecurityUtils.setSecurityManager(securityManager);
需求:
thymeleaf常用命名空间:
xmlns:th=http://www.thymeleaf.org
xmlns:sec=http://www.thymeleaf.org/extras/spring-security
xmlns:shiro=http://www.pollix.at/thymeleaf/shiro
html lang=en xmlns:th=http://www.thymeleaf.org
xmlns:sec=http://www.thymeleaf.org/extras/spring-security
xmlns:shiro=http://www.pollix.at/thymeleaf/shiro