SpringSecurity认证流程详解(附源码,复盘上次Redis缓存雪崩事故

.passwordParameter(“password”)

.loginPage("/toLoginPage")

.loginProcessingUrl("/login")

.successHandler(loginSuccessHandler)

.and()

.csrf()

.disable();

}`

此处有个大坑, 如果设置了成功的处理类, 我们就千万不要在配置类中写成功跳转的方法了, 这样会覆盖掉我们的成功处理器!

3. 前端用ajax请求并附加验证码校验

=====================

此处为天坑! 足足费了我快一天半才爬出来! 简直到处都是坑, 还有一个问题没解决…

总之不推荐这么干, 主要指用AJAX请求再用后台跳转

  • 首先, 我们要明确一点, AJAX会刷新局部页面, 这就造成了重定向请求没问题, 但是页面不跳转, 看请求头我们会发现url还是当前页面

  • 其次, SpringSecurity的认证是用request.getparameter()读出的, 因此无法解析AJAX请求传来的JSON, 我们要自己写过滤器解析

  • 最后, SpringSecurity在认证过滤器结束后会关闭request的Stream, 导致我们无法取出前端发来的数据, 需要我们再添加一个request, 再在成功的处理器中获得request中的对象

好了, 让我们来看看这个坑吧!

  • 前端代码


`









登录界面




 
 












 
 








`
  • 这里主要是$.ajaxSetup()方法, 可以定义全局的(同一个函数中的)ajax的一些参数, 尤其是里面的complete方法, 是在全部执行完之后调用的, 为了能强行跳转AJAX, 我们要天剑请求头, 我们在后面的后端代码中可以看到

  • 我们还需要写$.ajax()传递数据, 注意, json数据就算我们用json的格式写了, 还是要用JSON.stringify()方法转一下, 否则传到后端的不是JSON!

  • 此处有一个没有解决的问题, 不知道为什么不会走成功的回调函数, 只会走失败的回调函数

  • 自定义认证过滤器



`package com.wang.spring_security_framework.config.SpringSecurityConfig;



import com.alibaba.fastjson.JSON;

import org.springframework.http.MediaType;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;



import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.InputStream;

import java.util.Map;



//默认的提取用户名和密码是通过 request.getParameter() 方法来提取的, 所以通过form我们可以提取到

//但是如果我们用ajax传递的话, 就提取不到了, 需要自己写过滤器!

//这里不能写 @Component, 因为我们要在SpringSecurity配置类中注册 myCustomAuthenticationFilter 并配置

//否则会爆出重名的Bean!

public class MyCustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

@Override

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

//如果request请求是一个json同时编码方式为UTF-8

if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)

|| request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)) {

UsernamePasswordAuthenticationToken authRequest = null;



Map
  • 这里还是要强调一点, @Component会自动注册内部的全部的方法, 如果我们在别的地方@Bean了方法, 会报一些奇怪的错误, 本质上是冲突了!

  • 此处我们是用FastJSON将JSON转为了Map

  • 认证成功处理器



`package com.wang.spring_security_framework.config.SpringSecurityConfig;



import com.alibaba.fastjson.JSON;

import com.wang.spring_security_framework.service.CaptchaService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.context.SecurityContext;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import org.springframework.stereotype.Component;



import javax.servlet.ServletException;

import javax.servlet.ServletInputStream;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;



//登录成功处理

//我们不能在这里获得request了, 因为我们已经在前面自定义了认证过滤器, 做完后SpringSecurity会关闭inputStream流

@Component

public class LoginSuccessHandler implements AuthenticationSuccessHandler {

@Autowired

CaptchaService captchaService;



@Override

public void onAuthenticationSuccess(HttpServletRequest request,

HttpServletResponse response,

Authentication authentication) throws IOException, ServletException {

//我们从自定义的认证过滤器中拿到的authInfo, 接下来做验证码校验和跳转

Map
  • 这里需要注意一点, 我们需要从前面的Request拿到对象

  • addHeader里面我们为了重定向, 添加了响应头, 可以和前端的ajaxSetup对应着看

  • SpringSecurity配置类



`package com.wang.spring_security_framework.config;



import com.wang.spring_security_framework.config.SpringSecurityConfig.LoginSuccessHandler;

import com.wang.spring_security_framework.config.SpringSecurityConfig.MyCustomAuthenticationFilter;

import com.wang.spring_security_framework.service.UserService;

import com.wang.spring_security_framework.service.serviceImpl.UserDetailServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;



//SpringSecurity设置

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired

UserService userService;

@Autowired

UserDetailServiceImpl userDetailServiceImpl;

@Autowired

LoginSuccessHandler loginSuccessHandler;



//授权

@Override

protected void configure(HttpSecurity http) throws Exception {

//指定自定义的登录页面, 表单提交的url, 以及成功后的处理器

http.formLogin()

.loginPage("/toLoginPage")

.failureForwardUrl("/index")

.and()

.csrf()

.disable();

//        .failureForwardUrl();

//注销



//设置过滤器链, 添加自定义过滤器

http.addFilterAt(

myCustomAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class

);

//允许iframe

//        http.headers().frameOptions().sameOrigin();

}



//注册自定义过滤器

@Bean

MyCustomAuthenticationFilter myCustomAuthenticationFilter() throws Exception {

MyCustomAuthenticationFilter filter = new MyCustomAuthenticationFilter();

//设置过滤器认证管理

filter.setAuthenticationManager(super.authenticationManagerBean());

//设置filter的url

filter.setFilterProcessesUrl("/login");

//设置登录成功处理器

filter.setAuthenticationSuccessHandler(loginSuccessHandler);

//TODO 设置登录失败处理器



return filter;

}



//密码使用盐值加密 BCryptPasswordEncoder

//BCrypt.hashpw() ==> 加密

//BCrypt.checkpw() ==> 密码比较

//我们在数据库中存储的都是加密后的密码, 只有在网页上输入时是明文的

@Bean

public PasswordEncoder passwordEncoder() {

return new BCryptPasswordEncoder();

}



}` 
  • 这里主要干了两件事

  • 注册了我们自定义的过滤器

  • 在过滤器链中注册我们的过滤器

4. 后端只提供JSON让前端进行跳转

====================

这里主要修改了两处, 我们的成功处理器返回的是一个封装好的JSON, 同时我们在ajax的回调函数中写了页面跳转的逻辑

  • 成功处理器


`package com.wang.spring_security_framework.config.SpringSecurityConfig;



import com.alibaba.fastjson.JSON;

import com.wang.spring_security_framework.service.CaptchaService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.Authentication;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值