IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> 1.SpringSecurity -> 正文阅读

[网络协议]1.SpringSecurity

1. 认证授权的基础概念

1.1 什么是认证

进入移动互联网时代,大家每天都在刷手机,常用的软件有微信、支付宝、头条等,下边拿微信来
举例子说明认证相关的基本概念,在初次使用微信前需要注册成为微信用户,然后输入账号和密码
即可登录微信,输入账号和密码登录微信的过程就是认证。
系统为什么要认证?
认证是为了保护系统的隐私数据与资源,用户的身份合法方可访问该系统的资源。

认证 :用户认证就是判断一个用户的身份是否合法的过程,用户去访问系统资源时系统要求验证用
户的身份信息,身份合法方可继续访问,不合法则拒绝访问。常见的用户身份认证方式有:用户名
密码登录,二维码登录,手机短信登录,指纹认证等方式

1.2 什么是会话

用户认证通过后,为了避免用户的每次操作都进行认证可将用户的信息保证在会话中。会话就是系
统为了保持当前用户的登录状态所提供的机制,常见的有基于 session 方式、基于 token 方式等。

1.2.1基于 session 的认证方式

它的交互流程是,用户认证成功后,在服务端生成用户相关的数据保存在 session(当前会话)中,
发给客户端的 sesssion_id 存放到 cookie 中,这样用户客户端请求时带上 session_id 就可以
验证服务器端是否存在 session 数据,以此完成用户的合法校验,当用户退出系统或 session 过
期销毁时,客户端的 session_id 也就无效了。 保持有状态的链接

1.2.2基于 token 方式认证方式

它的交互流程是,用户认证成功后,服务端生成一个 token 发给客户端,客户端可以放到 cookie 或
localStorage 等存储中,每次请求时带上 token,服务端收到 token 通过验证后即可确认用户身
份。
基于 session 的认证方式由 Servlet 规范定制,服务端要存储 session 信息需要占用内存资源,
客户端需要支持 cookie;基于 token 的方式则一般不需要服务端存储 token,并且不限制客户端
的存储方式。如今移动互联网时代更多类型的客户端需要接入系统,系统多是采用前后端分离的架
构进行实现,所以基于 token 的方式更适合。

1.3 什么是授权

还拿微信来举例子,微信登录成功后用户即可使用微信的功能,比如,发红包、发朋友圈、添加好
友等,没有绑定银行卡的用户是无法发送红包的,绑定银行卡的用户才可以发红包,发红包功能、
发朋友圈功能都是微信的资源即功能资源,用户拥有发红包功能的权限才可以正常使用发送红包功
能,拥有发朋友圈功能的权限才可以使用发朋友圈功能,这个根据用户的权限来控制用户使用资源
的过程就是授权。

1.3.1为什么要授权?

认证是为了保证用户身份的合法性,授权则是为了更细粒度的对隐私数据进行划分,授权是在认证
通过后发生的,控制不同的用户能够访问不同的资源。
授权: 授权是用户认证通过根据用户的权限来控制用户访问资源的过程,拥有资源的访问权限则正
常访问,没有权限则拒绝访问

1.4 授权的数据模型

如何进行授权即如何对用户访问资源进行控制,首先需要学习授权相关的数据模型。
授权可简单理解为 Who 对 What(which)进行 How 操作,包括如下:
Who,即主体(Subject),主体一般是指用户,也可以是程序,需要访问系统中的资源。 What,
即资源(Resource),如系统菜单、页面、按钮、代码方法、系统商品信息、系统订单信息等。系
统菜单、页面、按钮、代码方法都属于系统功能资源,对于 web 系统每个功能资源通常对应一个 URL;
系统商品信息、系统订单信息都属于实体资源(数据资源),实体资源由资源类型和资源实例组成,
比如商品信息为资源类型,商品编号 为 001 的商品为资源实例。 How,权限/许可(Permission),
规定了用户对资源的操作许可,权限离开资源没有意义,如用户查询权限、用户添加权限、某个代
码方法的调用权限、编号为 001 的用户的修改权限等,通过权限可知用户对哪些资源都有哪些操作
可。
主体、资源、权限关系如下图:
在这里插入图片描述
主体、资源、权限相关的数据模型如下:
主体(用户 id、账号、密码、…)
资源(资源 id、资源名称、访问地址、…)
权限(权限 id、权限标识、权限名称、资源 id、…)
角色(角色 id、角色名称、…)
角色和权限关系(角色 id、权限 id、…)
主体(用户)和角色关系(用户 id、角色 id、…)
主体(用户)、资源、权限关系如下图
在这里插入图片描述
通常企业开发中将资源和权限表合并为一张权限表,如下:
资源(资源 id、资源名称、访问地址、…)
权限(权限 id、权限标识、权限名称、资源 id、…)
合并为:
权限(权限 id、权限标识、权限名称、资源名称、资源访问地址、…)
修改后数据模型之间的关系如下图
在这里插入图片描述

1.5 RBAC

用户,角色,权限 本质:就是把权限打包给角色,分配给用户
RBAC 一般指基于角色的访问控制 权限
基于角色的访问控制(RBAC)是实施面向企业安全策略的一种有效的访问控制方式。

1.5.1基于角色的访问控制

RBAC 基于角色的访问控制(Role-Based Access Control)是按角色进行授权,比如:主体的角
色为总经理可以查询企业运营报表,查询员工工资信息等

根据上图中的判断逻辑,授权代码可表示如下:
if(主体.hasRole(“总经理角色 id”)){
查询工资
}

如果上图中查询工资所需要的角色变化为总经理和部门经理,此时就需要修改判断逻辑为“判断用户
的角色是否是总经理或部门经理”,修改代码如下:
if(主体.hasRole(“总经理角色 id”) || 主体.hasRole(“部门经理角色 id”)){
查询工资
}

根据上边的例子发现,当需要修改角色的权限时就需要修改授权的相关代码,系统可扩展性差。

1.5.2基于资源的访问控制

RBAC 基于资源的访问控制(Resource-Based Access Control)是按资源(或权限)进行授权,
比如:用户必须具有查询工资权限才可以查询员工工资信息等,如下的判断
if(主体.hasPermission(“查询工资”) ){
查询工资
}
优点:系统设计时定义好查询工资的权限标识,即使查询工资所需要的角色变化为总经理和部门经
理也不需要修改授权代码,系统可扩展性强。

2. Spring Security 简介

官网: https://spring.io/projects/spring-security
英 文 文 档 :
https://docs.spring.io/spring-security/site/docs/5.4.1/reference/html5/
中文文档: https://www.springcloud.cc/spring-security.html

2.1 什么是 SpringSecurity

Spring Security 是一个能够为基于 Spring 的企业应用系统提供声明式的安全访问控制解决方案
的安全框架。它提供了一组可以在 Spring 应用上下文中配置的 Bean,充分利用了 Spring IoC,
DI(控制反转 Inversion of Control ,DI:Dependency Injection 依赖注入)和 AOP(面向切
面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量
重复代码的工作。可以一句话来概括,SpringSecurity 是一个安全框架。
2.2 同类产品(和 shiro 对比)
同类产品中的佼佼者就是 Shiro 了,那这两者有什么区别的吗?
2.2.1共同点
认证功能
授权功能
加密功能
会话功能
remeberMe 功能
……

就功能上来说基本是相似。
2.2.2不同点
优点:
Spring Security 基于 Spring 开发,项目中如果使用 Spring 作为基础,配合 Spring Security
做权限更加方便。而 Shiro 需要和 Spring 进行整合。
Spring Security 功能比 Shiro 更加丰富,例如安全防护方面。
Spring Security 社区资源相对比 Shiro 更加丰富。
如果使用的是 Spring Boot,Spring Cloud 的话,三者可以无缝集成。
缺点:
Shiro 的配置和使用比较简单,Spring Security 上手复杂些。
Shiro 依赖性低,不需要任何框架和容器,可以独立运行,而 Spring Security 依赖 Spring 容器。

3. Spring Security项目

3.1 创建项目

<?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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sxt</groupId>
<artifactId>security-hello</artifactId>
<version>1.0</version>
9
<name>security-hello</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--security 的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

3.2配置启动类

package com.zuxia;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
	@SpringBootApplication
	@EnableWebSecurity // 启用 security 在 5.X 版本之后可以不用加,默认就是开启的
public class SecurityHelloApplication {
	public static void main(String[] args) {
	SpringApplication.run(SecurityHelloApplication.class, args);
	}
}

3.3 创建 HelloController

package com.zuxia.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
@GetMapping("hello")
public String hello() {
return "hello security";
}
}

3.4启动测试访问
http://localhost:8080/hello
发现我们无法访问 hello 这个请求,这是因为 spring Security
在这里插入图片描述
登录后就可以访问我们的 hello
3.5 测试退出
访问: http://localhost:8080/logout

3.6自定义密码登录(yml 配置文件方式)

spring:
	security:
		user:
			name: admin #默认使用的用户名
			password: 123456 #默认使用的密码

3.7重启使用 admin 和 123456 登录即可

4.Spring Security 配置多用户

4.1 概述

认证就是登陆,我们现在没有连接数据库,那么我们可以模拟下用户名和密码

4.2 创建认证的配置类 WebSecurityConfig

package com.zuxia.config;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationManage
rBuilder;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapt
er;
/**
* @Author 武汉尚学堂
* 安全配置
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置用户信息,模拟内存用户数据
*
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置两个用户,sxt 和 test
auth.inMemoryAuthentication()
.withUser("admin")
.password("123")
.roles("SXT_ADMIN")
.and()
.withUser("test")
.password("123")
.roles("TEST");
}
}

4.3 启动测试

我们只要添加了安全配置类,那么我们在 yml 里面的配置就失效了
我们使用 admin/123 访问登录,发现控制台报错了
在这里插入图片描述

这个是因为 spring Sercurity 强制要使用密码加密,当然我们也可以不加密,但是官方要求是不
管你是否加密,都必须配置一个类似 Shiro 的凭证匹配器

4.4 修改 WebSecurityConfig 添加加密器

package com.zuxia.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.Authenticat
ionManagerBuilder;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfig
urerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 安全配置
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置用户信息,模拟内存用户数据
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置两个用户,sxt 和 test
	auth.inMemoryAuthentication()
	.withUser("admin")
	.password(passwordEncoder().encode("123"))
	.roles("SXT_ADMIN")
	.and()
	.withUser("test")
	.password(passwordEncoder().encode("123"))
	.roles("TEST");
	}
	/*
	* 从 Spring5 开始,强制要求密码要加密
	* 如果非不想加密,可以使用一个过期的 PasswordEncoder 的实例 NoOpPasswordEncoder,
	* 但是不建议这么做,毕竟不安全。
	*
	* @return
	*/
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}

4.5 重启测试

两个用户都可以登录成功了

4.6 如何获取当前登录用户的信息(两种方式)

我们添加获取当前用户信息的 Controlle

	/**
	* 获取当前用户信息,直接在参数中注入 Principal 对象
	* 此对象是登录后自动写入 UsernamePasswordAuthenticationToken 类中
	*
	* @param principal
	* @return
	*/
	@GetMapping("userInfo")
	public Principal getUserInfo(Principal principal) {
		return principal;
	}
	/**
	* SecurityContextHolder.getContext()获取安全上下文对象
	* 就是那个保存在 ThreadLocal 里面的安全上下文对象
	* 总是不为 null(如果不存在,则创建一个 authentication 属性为 null 的 empty 安全上下文对象)
	* 获取当前认证了的 principal(当事人),或者 request token (令牌)
	* 如果没有认证,会是 null,该例子是认证之后的情况
	*/
	@GetMapping("userInfo2")
	public Object getUserInfo2() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		return authentication;
	}

测试访问
http://localhost:8080/userInfo
http://localhost:8080/userInfo2

5.Spring Security 用户,角色,权限拦截配置

5.1 角色和权限的配置,修改 WebSecurityConfig

package com.zuxia.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
	/**
	* 安全配置类
	*/
	@Configuration
	public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	/**
	* 配置用户信息,模拟内存用户数据
	* 重点说明:
	* 在开发中,我们一般只针对权限,很少去使用角色
	* 后面的讲解中我们以权限为主也就是 authorities 这里面的东西
	18
	*
	* @param auth
	* @throws Exception
	*/
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	// 在内存中配置两个用户,sxt 和 test
	auth.inMemoryAuthentication()
	.withUser("admin")
	.password(passwordEncoder().encode("123"))
	.roles("SXT")
	.authorities("sys:save", "sys:del", "sys:update", "sys:query") // 给 sxt 这个用户加四个权限
	.and()
	.withUser("test")
	.password(passwordEncoder().encode("123"))
	.roles("TEST")
	.authorities("sys:save", "sys:query") // 给 test 这个用户加两个权限
	.and().withUser("admin2")
	.password(passwordEncoder().encode("123"))
	.roles("ADMIN"); // 给 admin 这个用户一个 ADMIN 的角色,如果角色和权限都给了,那么角色就失效了
	}
	/**
	* 配置 http 请求验证等
	*
	* @param http
	* @throws Exception
	*/
	@Override
	protected void configure(HttpSecurity http) throws Exception {
	// 注释掉他自己的方法 走我们自己的
	// super.configure(http);
	// 给一个表单登陆 就是我们的登录页面,登录成功或者失败后走我们的 url
	http.formLogin().successForwardUrl("/welcome").failureForwardUrl("/fail");
	// 匹配哪些 url,需要哪些权限才可以访问 当然我们也可以使用链式编程的方式
	http.authorizeRequests()
	.antMatchers("/query").hasAnyAuthority("sys:query")
	.antMatchers("/save").hasAnyAuthority("sys:save")
	.antMatchers("/del").hasAnyAuthority("sys:del")
	.antMatchers("/update").hasAnyAuthority("sys:update")
	.antMatchers("/admin2/**").hasRole("ADMIN")
	.anyRequest().authenticated(); // 其他所有的请求都需要登录才能进行
	}
	/*
	* 从 Spring5 开始,强制要求密码要加密
	* 如果非不想加密,可以使用一个过期的 PasswordEncoder 的实例 NoOpPasswordEncoder,
	* 但是不建议这么做,毕竟不安全。
	*
	* @return
	*/
	@Bean
	public PasswordEncoder passwordEncoder() {
	return new BCryptPasswordEncoder();
	}
}

5.2 添加几个 Controller 接口

	/**
	* 登录成功后的欢迎页面
	* @return
	*/
	@PostMapping("welcome")
	public String welcome() {
	return "我是登录成功后的欢迎页面 welcome";
	}
	@GetMapping("save")
	public String save() {
	return "我是 save 页面";
	}
	@GetMapping("del")
	public String del() {
	return "我是 del 页面";
	}
	@GetMapping("update")
	public String update() {
	return "我是 update 页面";
	}
	@GetMapping("query")
	public String query() {
	return "我是 query 页面";
	}
	@GetMapping("admin/hello")
	public String admin() {
	return "我是只有 admin 角色才可以访问的";
	}

5.3 启动测试

使用 admin/123 登录后 这几个接口都可以访问
使用 test/123 登录后,访问/update 和/del 会报错跳到 403 页面
使用 admin2/123 登录后,只能访问/admin/hello,访问其他接口会跳到 403 页

5.4 我们在static下添加一个 403.html,让他报错后跳到我们自己的页面

6.Spring Security 返回 JSON(前后端分离)

在上面的例子中,我们返回的是 403 页面,但是在开发中,如 RestAPI 风格的数据,是不能返回一
个页面,而应该是给一个 json

6.1 添加拒接访问(没有权限)处理器 RestAuthorizationAccessDeniedHandler

package com.zuxia.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
	/**
	* 拒绝访问的处理器
	*/
	@Configuration
	public class RestAuthorizationAccessDeniedHandler implements AccessDeniedHandler {
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
	AccessDeniedException e) throws IOException, ServletException {
	// 设置数据类型
	response.setContentType("application/json;charset=utf-8");
	// 封装数据
	Map<String, Object> data = new HashMap<>();
	data.put("code", "403");
	data.put("msg", "您没有访问权限");
	// 拿到响应流
	PrintWriter writer = response.getWriter();
	// 创建类型转换器
	ObjectMapper objectMapper = new ObjectMapper();
	String s = objectMapper.writeValueAsString(data);
	// 将数据写出去
	writer.write(s);
	writer.flush();
	writer.close();
	}
}

登录成功或者失败都返回 JSON,我们需要自定义处理器

登录成功返回 json 的处理器

package com.zuxia.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
	/**
	* 登录成功的处理器
	*/
	@Configuration
	public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse
	response, Authentication authentication) throws IOException {
	response.setContentType("application/json;charset=utf-8");
	PrintWriter pw = response.getWriter();
	Map<String, Object> map = new HashMap<>();
	map.put("code", 200);
	// 将用户信息放进去
	map.put("msg", authentication.getPrincipal());
	pw.write(new ObjectMapper().writeValueAsString(map));
	pw.flush();
	pw.close();
	}
}

登录失败返回 json 的处理器

package com.zuxia.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
	/**
	* 登录失败的处理器
	*/
	@Configuration
	public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse
			response, AuthenticationException exception) throws IOException, ServletException {
			response.setContentType("application/json;charset=utf-8");
			PrintWriter pw = response.getWriter();
			Map<String, Object> map = new HashMap<>();
			map.put("code", 401);
			if (exception instanceof LockedException) {
				map.put("msg", "账户被锁定,登陆失败!");
			} else if (exception instanceof BadCredentialsException) {
				map.put("msg", "账户或者密码错误,登陆失败!");
			} else if (exception instanceof DisabledException) {
				map.put("msg", "账户被禁用,登陆失败!");
			} else if (exception instanceof AccountExpiredException) {
				map.put("msg", "账户已过期,登陆失败!");
			} else if (exception instanceof CredentialsExpiredException) {
				map.put("msg", "密码已过期,登陆失败!");
			} else {
				map.put("msg", "登陆失败!");
			}
			System.out.println(exception.getClass().getSimpleName());
			pw.write(new ObjectMapper().writeValueAsString(map));
			pw.flush();
			pw.close();
	}
}

6.2修改 WebSecurityConfig 出现拒接访问、 WebSecurityConfig 登录成功或失败走自己的处理器

	/**
	* 将自定义的拒绝访问处理器注入进来
	*/
	@Autowired
	private AccessDeniedHandler accessDeniedHandler;
	/**
	* 将自定义的登录成功处理器注入进来
	*/
	@Autowired
	private AuthenticationSuccessHandler authenticationSuccessHandler;
	/**
	* 将自定义的登录失败处理器注入进来
	*/
	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;
	/**
	* 配置 http 请求验证等
	*
	* @param http
	* @throws Exception
	*/
	@Override
	protected void configure(HttpSecurity http) throws Exception {
	// 注释掉他自己的方法 走我们自己的
	// super.configure(http);
	// 给一个异常处理器,走我们自定义的拒绝访问处理器
	http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
	// 给一个表单登陆 就是我们的登录页面,登录成功或者失败后走我们的 url
	// http.formLogin().successForwardUrl("/welcome").failureForwardUrl("/fail");
	
	// 登录成功或者失败走自己的处理器
	http.formLogin().successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler);
	// 匹配哪些 url,需要哪些权限才可以访问 当然我们也可以使用链式编程的方式
	http.authorizeRequests()
	.antMatchers("/query").hasAnyAuthority("sys:query")
	.antMatchers("/save").hasAnyAuthority("sys:save")
	.antMatchers("/del").hasAnyAuthority("sys:del")
	.antMatchers("/update").hasAnyAuthority("sys:update")
	.antMatchers("/admin/**").hasRole("ADMIN")
	.anyRequest().authenticated(); // 其他所有的请求都需要登录才能进行
}
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-12-01 18:03:38  更:2021-12-01 18:03:54 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年7日历 -2024/7/6 8:42:18-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码