spring security 之自定义表单登录源码跟踪
上一节我们跟踪了security的默认登录页的源码,可以参考这里:https://www.cnblogs.com/process-h/p/15522267.html 这节我们来看看如何自定义单表认证页及源码跟踪。
为了实现自定义表单及登录页,我们需要编写自己的WebSecurityConfig类,继承了WebSecurityConfigurerAdapter对象,通过重写configure方法,定义自己的登录页路径及失败跳转的路径。
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/css/**", "/index").permitAll()
.antMatchers("/user/**").hasRole("USER")
)
.formLogin(formLogin ->
formLogin
.loginPage("/login")
.failureUrl("/login-error")
);
}
// @formatter:on
@Bean
public UserDetailsService userDetailsService() {
UserDetails userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(userDetails);
}
}
我们通过引入Thymeleaf模板来实现跳转
@Controller
public class MainController {
@RequestMapping("/")
public String root() {
return "redirect:/index";
}
@RequestMapping("/index")
public String index() {
return "index";
}
@RequestMapping("/user/index")
public String userIndex() {
return "user/index";
}
@RequestMapping("/login")
public String login() {
return "login";
}
@RequestMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("loginError", true);
return "login";
}
}
上一节我们提到了WebSecurityConfig类,它会有一个init方法
@Override
public void init(WebSecurity web) throws Exception {
HttpSecurity http = getHttp();
web.addSecurityFilterChainBuilder(http).postBuildAction(() -> {
FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);
web.securityInterceptor(securityInterceptor);
});
}
这里提到了HttpSecurity对象,顾名思义,它的作用就是保证Http请求的安全,那么它是如何保证http请求的安全的呢?我们来看看getHttp()方法
protected final HttpSecurity getHttp() throws Exception {
if (this.http != null) {
return this.http;
}
// 初始化认证事件发布者,也就是定义了一些异常跟异常事件类之前的映射关系
AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();
this.localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);
// 初始化认证管理者
AuthenticationManager authenticationManager = authenticationManager();
this.authenticationBuilder.parentAuthenticationManager(authenticationManager);
Map<Class<?>, Object> sharedObjects = createSharedObjects();
this.http = new HttpSecurity(this.objectPostProcessor, this.authenticationBuilder, sharedObjects);
if (!this.disableDefaults) {
// 默认情况下会去加载配置
applyDefaultConfiguration(this.http);
ClassLoader classLoader = this.context.getClassLoader();
List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader
.loadFactories(AbstractHttpConfigurer.class, classLoader);
for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
this.http.apply(configurer);
}
}
configure(this.http);
return this.http;
}
// 默认认证事件发布者
public DefaultAuthenticationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
addMapping(BadCredentialsException.class.getName(), AuthenticationFailureBadCredentialsEvent.class);
addMapping(UsernameNotFoundException.class.getName(), AuthenticationFailureBadCredentialsEvent.class);
addMapping(AccountExpiredException.class.getName(), AuthenticationFailureExpiredEvent.class);
addMapping(ProviderNotFoundException.class.getName(), AuthenticationFailureProviderNotFoundEvent.class);
addMapping(DisabledException.class.getName(), AuthenticationFailureDisabledEvent.class);
addMapping(LockedException.class.getName(), AuthenticationFailureLockedEvent.class);
addMapping(AuthenticationServiceException.class.getName(), AuthenticationFailureServiceExceptionEvent.class);
addMapping(CredentialsExpiredException.class.getName(), AuthenticationFailureCredentialsExpiredEvent.class);
addMapping("org.springframework.security.authentication.cas.ProxyUntrustedException",
AuthenticationFailureProxyUntrustedEvent.class);
addMapping("org.springframework.security.oauth2.server.resource.InvalidBearerTokenException",
AuthenticationFailureBadCredentialsEvent.class);
}
我们来看看applyDefaultConfiguration这个方法,在上一节有讲到,这里是给httpSecurity对象配置一些默认的配置,比如默认会开启csrf跨站请求伪造防护,添加WebAsyncManagerIntegrationFilter过滤器,添加默认的登录页配置DefaultLoginPageConfigurer等。
private void applyDefaultConfiguration(HttpSecurity http) throws Exception {
http.csrf();
http.addFilter(new WebAsyncManagerIntegrationFilter());
http.exceptionHandling();
http.headers();
http.sessionManagement();
http.securityContext();
http.requestCache();
http.anonymous();
http.servletApi();
http.apply(new DefaultLoginPageConfigurer<>());
http.logout();
}
回到调用applyDefaultConfiguration()的主方法这里,执行完if (!this.disableDefaults) {}分支之后,会调用自身的configure(this.http);方法,也就是我们自定义的WebSecurityConfig类中重写的方法,会去执行我们的表单登录配置策略。
.formLogin(formLogin ->
formLogin
.loginPage("/login")
.failureUrl("/login-error")
);
@Override
public FormLoginConfigurer<H> loginPage(String loginPage) {
return super.loginPage(loginPage);
}
protected T loginPage(String loginPage) {
setLoginPage(loginPage);
updateAuthenticationDefaults();
this.customLoginPage = true;
return getSelf();
}
点击.loginPage("/login")方法,再点击super.loginPage(loginPage); 可以看到登录页已经被重写了,自定义登录页标志也被写成了true。
自定义表单登录页及源码跟踪就到这里,过程中还发现了跟security最为密切的filter顺序定义,在该FilterOrderRegistration类的构造方法中,定义了security中可能会用到的所有filter的顺序,有兴趣的读者自行阅读下。登录相关的源码跟的线条比较粗,接下来该看看认证跟授权的部分了。
spring security 之自定义表单登录源码跟踪的更多相关文章
- SpringBoot集成Spring Security(4)——自定义表单登录
通过前面三篇文章,你应该大致了解了 Spring Security 的流程.你应该发现了,真正的 login 请求是由 Spring Security 帮我们处理的,那么我们如何实现自定义表单登录呢, ...
- SpringSecurity 自定义表单登录
SpringSecurity 自定义表单登录 本篇主要讲解 在SpringSecurity中 如何 自定义表单登录 , SpringSecurity默认提供了一个表单登录,但是实际项目里肯定无法使用的 ...
- SpringBoot2.0整合SpringSecurity实现自定义表单登录
我们知道企业级权限框架一般有Shiro,Shiro虽然强大,但是却不属于Spring成员之一,接下来我们说说SpringSecurity这款强大的安全框架.费话不多说,直接上干货. pom文件引入以下 ...
- SpringBoot 整合 spring security oauth2 jwt完整示例 附源码
废话不说直接进入主题(假设您已对spring security.oauth2.jwt技术的了解,不懂的自行搜索了解) 依赖版本 springboot 2.1.5.RELEASE spring-secu ...
- ddms(基于 Express 的表单管理系统)源码学习
ddms是基于express的一个表单管理系统,今天抽时间看了下它的代码,其实算不上源码学习,只是对它其中一些小的开发技巧做一些记录,希望以后在项目开发中能够实践下. 数据层封装 模块只对外暴露mod ...
- JS表单验证源码(带错误提示及密码等级)
先晒图 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...
- jquery表单验证源码
/**数据验证完整性**/$.fn.Validform = function () { var Validatemsg = ""; var Validateflag = ...
- Spring Security 表单登录
1. 简介 本文将重点介绍使用Spring Security登录. 本文将构建在之前简单的Spring MVC示例之上,因为这是设置Web应用程序和登录机制的必不可少的. 2. Maven 依赖 要将 ...
- spring security之 默认登录页源码跟踪
spring security之 默认登录页源码跟踪 2021年的最后2个月,立个flag,要把Spring Security和Spring Security OAuth2的应用及主流程源码研究透 ...
随机推荐
- python杀死Windows后台程序
检测 "sogou-gui.exe" 的进程可用tasklist命令 tasklist /FI "IMAGENAME eq sogou-gui.exe" FI: ...
- 大型项目源码集合「GitHub 热点速览 v.21.39」
作者:HelloGitHub-小鱼干 代码,尤其是优雅规范的代码,一直都是学习编程技巧的捷径.虽然有实用的代码小片段,能拯救当前业务的燃眉之急,但是真要去提升自己的技能还是得从大型的项目,尤其是有一定 ...
- P5180-[模板]支配树
正题 题目链接:https://www.luogu.com.cn/problem/P5180 题目大意 给出\(n\)个点的一张有向图,求每个点支配的点数量. \(1\leq n\leq 2\time ...
- C# .NET Core 3.1中使用 MongoDB.Driver 更新嵌套数组元素和关联的一些坑
C# .NET Core 3.1中使用 MongoDB.Driver 更新数组元素和关联的一些坑 前言: 由于工作的原因,使用的数据库由原来的 关系型数据库 MySQL.SQL Server 变成了 ...
- macbook air m1上传文件到github
一,首先安装git,打开ssh文件里的id_rsa.pub,然后复制所有内容. 二,github上申请自己的账号,右上角settings里选择SSH and GPG keys,点击new ssh ke ...
- SpringBoot入门05-全局配置文件
springboot全局配置文件作用是设置或修改默认设置 springboot全局配置文件有下面两种方式 application.xml配置文件 示例 server.port=8088 server. ...
- 用C++生成solidity语言描述的buchi自动机的初级经验
我的项目rvtool(https://github.com/Zeraka/rvtool)中增加了生成solidity语言格式的监控器的模块. solidity特殊之处在于,它是运行在以太坊虚拟机环境中 ...
- Golang通脉之基础入门
为什么要学 Go 性能优越感:Go 极其地快,其性能与 Java 或 C++相似.在使用中,Go 一般比 Python 要快 30 倍: 序列化/去序列化.排序和聚合中表现优异: 开发者效率较高:多种 ...
- BPMN 學習實例
什麼是業務流程圖? What is BPMN 業務流程建模符號(BPMN)是業務流程建模的一種方法.它基於統一建模語言(UML)中活動圖的概念,以圖形符號(業務流程圖)支持業務流程的規範.BPMN為企 ...
- springcloud整合seata
springcloud整合seata 一.背景 二.项目结构 三.实现功能: 四.项目使用到的技术 五.整合步骤 1.引入spring-cloud-starter-alibaba-seata jar包 ...