2024年Java最全SpringSecurity认证流程详解(附源码),Java开发还会吃香吗

那么如何才能正确的掌握Redis呢?

为了让大家能够在Redis上能够加深,所以这次给大家准备了一些Redis的学习资料,还有一些大厂的面试题,包括以下这些面试题

  • 并发编程面试题汇总

  • JVM面试题汇总

  • Netty常被问到的那些面试题汇总

  • Tomcat面试题整理汇总

  • Mysql面试题汇总

  • Spring源码深度解析

  • Mybatis常见面试题汇总

  • Nginx那些面试题汇总

  • Zookeeper面试题汇总

  • RabbitMQ常见面试题汇总

JVM常频面试:

Redis高频面试笔记:基础+缓存雪崩+哨兵+集群+Reids场景设计

Mysql面试题汇总(一)

Redis高频面试笔记:基础+缓存雪崩+哨兵+集群+Reids场景设计

Mysql面试题汇总(二)

Redis高频面试笔记:基础+缓存雪崩+哨兵+集群+Reids场景设计

Redis常见面试题汇总(300+题)

Redis高频面试笔记:基础+缓存雪崩+哨兵+集群+Reids场景设计

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

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

import org.springframework.security.core.Authentication;

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

import org.springframework.stereotype.Component;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

//登录成功处理, 用于比对验证码

@Component

public class LoginSuccessHandler implements AuthenticationSuccessHandler {

@Autowired

CaptchaService captchaService;

@Override

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

//校验验证码

Boolean verifyResult = captchaService.versifyCaptcha(request.getParameter(“token”),

request.getParameter(“inputCode”));

if (verifyResult) {

response.sendRedirect(“/index”);

} else {

response.sendRedirect(“/toLoginPage”);

}

}

}`

  • 在SpringSecurity的配置类中使用我们自己定义的处理类

`@Override

protected void configure(HttpSecurity http) throws Exception {

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

http.formLogin()

.usernameParameter(“username”)

.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;



### 最后

作为过来人,小编是整理了很多进阶架构视频资料、面试文档以及PDF的学习资料,针对上面一套系统大纲小编也有对应的相关进阶架构视频资料

![](https://img-blog.csdnimg.cn/img_convert/aabc4bb55a9a08e01393d218dd00911f.webp?x-oss-process=image/format,png)
![](https://img-blog.csdnimg.cn/img_convert/b213859bd39672a43c5783f311b0422a.webp?x-oss-process=image/format,png)



> **本文已被[CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】](https://bbs.csdn.net/topics/618154847)收录**

**[需要这份系统化的资料的朋友,可以点击这里获取](https://bbs.csdn.net/topics/618154847)**

过滤器

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;



### 最后

作为过来人,小编是整理了很多进阶架构视频资料、面试文档以及PDF的学习资料,针对上面一套系统大纲小编也有对应的相关进阶架构视频资料

[外链图片转存中...(img-4AuhkJ98-1714871945111)]
[外链图片转存中...(img-mJTevnWx-1714871945111)]



> **本文已被[CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】](https://bbs.csdn.net/topics/618154847)收录**

**[需要这份系统化的资料的朋友,可以点击这里获取](https://bbs.csdn.net/topics/618154847)**

  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security是一个在Java应用程序中提供身份验证和授权的框架。它通过使用各种身份验证和授权技术,帮助开发人员实现应用程序的安性。 在Spring Security中,身份验证包括验证用户的身份以确保其是合法的,并且授权包括确定用户是否有权访问特定功能或资。以下是Spring Security中的一些关键概念和用法: 1. 身份验证:Spring Security提供了许多身份验证机制,例如基于表单的身份验证、基于HTTP基本身份验证、基于LDAP的身份验证等。开发人员可以选择适合他们应用程序需求的身份验证机制。 2. 授权:Spring Security使用许可(Permission)和角色(Role)的概念来控制访问权限。可以使用特定的注解或编程方式将这些权限和角色应用到方法或URL上。 3. 认证和授权流程:Spring Security在认证和授权过程中使用了一系列的过滤器和提供者。它们分别负责处理身份验证和授权的不同方面。开发人员可以根据需要定制这些组件来满足自己的应用程序需求。 4. AccessDecisionManager:这是Spring Security中的一个重要组件,用于决定用户是否有权限访问特定的资或功能。开发人员可以实现自己的AccessDecisionManager来根据自己的逻辑进行权限决策。 5. UserDetails:在Spring Security中,用户信息通过UserDetails接口进行封装。开发人员可以根据自己的需求实现自定义的UserDetails接口,并提供用户的身份验证和授权信息。 6. 匿名认证:Spring Security支持为匿名用户建立一个匿名Authentication对象。这样,无需再对匿名用户进行额外的验证,可以直接将其当作正常的Authentication对象来使用。 综上所述,Spring Security提供了面的身份验证和授权机制来保护应用程序的安性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值