最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Security賬戶與密碼驗證實現(xiàn)過程

 更新時間:2023年03月28日 08:27:42   作者:T.Y.Bao  
這篇文章主要介紹了Spring Security賬戶與密碼驗證實現(xiàn)過程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧

這里使用Spring Boot 2.7.4版本,對應Spring Security 5.7.3版本

本文樣例代碼地址: spring-security-oauth2.0-sample

關(guān)于Username/Password認證的基本流程和基本方法參見官網(wǎng) Username/Password Authentication

Introduction

Username/Password認證主要就是Spring Security 在 HttpServletRequest中讀取用戶登錄提交的信息的認證機制。

Spring Security提供了登錄頁面,是前后端不分離的形式,前后端分離時的配置需另加配置。本文基于前后端分離模式來敘述。

基本流程如下:

Username/Password認證可分為兩部分:

  • 從HttpServletRequest中獲取用戶登錄信息
  • 從密碼存儲處獲取密碼并比較

關(guān)于獲取獲取用戶登錄信息,Spring Security支持三種方式(基本用的都是Form表單提交,即POST方式提交):

  • Form
  • Basic
  • Digest

關(guān)于密碼的獲取和比對,關(guān)注下面幾個類和接口:

  • UsernamePasswordAuthenticationFilter: 過濾器,父類AbstractAuthenticationProcessingFilter中組合了AuthenticationManagerAuthenticationManager的默認實現(xiàn)ProviderManager中又組合了多個AuthenticationProvider,該接口實現(xiàn)類,有一個DaoAuthenticationProvider負責獲取用戶密碼以及權(quán)限信息,DaoAuthenticationProvider又把責任推卸給了UserDetailService。
  • PasswordEncoder : 密碼加密方式
  • UserDetails : 代表用戶,包括 用戶名、密碼、權(quán)限等信息
  • UserDetailsService : 最終實際調(diào)用獲取 UserDetails的接口,通常用戶實現(xiàn)。

整個流程的UML圖如下:

前后端分離模式下配置

先來看對SecurityFilterChain的配置:

@Configuration
@EnableMethodSecurity()
@RequiredArgsConstructor
public class SecurityConfig {
	// 自定義成功處理,主要存儲登錄信息并返回jwt
	private final LoginSuccessHandler loginSuccessHandler;
	// 自定義失敗處理,返回json格式而非默認的html
    private final LoginFailureHandler loginFailureHandler;
    private final CustomSessionAuthenticationStrategy customSessionAuthenticationStrategy;
	...
	@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    	// 設(shè)置登錄成功后session處理, 認證成功后
        // SessionAuthenticationStrategy的最早執(zhí)行,詳見AbstractAuthenticationProcessingFilter
        // 執(zhí)行順序:
        // 1. SessionAuthenticationStrategy#onAuthentication
        // 2. SecurityContextHolder#setContext
        // 3. SecurityContextRepository#saveContext
        // 4. RememberMeServices#loginSuccess
        // 5. ApplicationEventPublisher#publishEvent
        // 6. AuthenticationSuccessHandler#onAuthenticationSuccess
        http.sessionManagement().sessionAuthenticationStrategy(customSessionAuthenticationStrategy);
		...
		// 前后端不分離,可指定html返回。該項未測試
        // http.formLogin().loginPage("login").loginProcessingUrl("/hello/login");
        // 前后端分離下username/password登錄
        http.formLogin()
                .usernameParameter("userId")
                .passwordParameter("password")
                // 前端登陸頁面對這個url提交username/password即可
                // 必須為Post請求,且Body格式為x-www-form-urlencoded,如果要接受application/json格式,需另加配置
                .loginProcessingUrl("/hello/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler);
                //  .securityContextRepository(...)  // pass
       ...
       return http.build();
	}
	...
}

使用Postman測試:

登錄成功登陸失敗

AbstractAuthenticationProcessingFilter

該類是UsernamePasswordAuthenticationFilterOAuth2LoginAuthenticationFilter的父類,使用模板模式構(gòu)建。

UsernamePasswordAuthenticationFilter只負責從HttpServletRequest中獲取用戶提交的用戶名密碼,而真正去認證、事件發(fā)布、SessionAuthenticationStrategy、AuthenticationSuccessHandler、AuthenticationFailureHandler、SecurityContextRepository、RememberMeServices這些內(nèi)容均組合在AbstractAuthenticationProcessingFilter中。

public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean
		implements ApplicationEventPublisherAware, MessageSourceAware {
	...
	// 委托給子類ProviderManager執(zhí)行認證,最終由DaoAuthenticationProvider認證
	// DaoAuthenticationProvider中會調(diào)用UserDetailsService#loadUserByUsername(username)接口方法
	// 我們只需實現(xiàn)該UserDetailsService接口注入Bean容器即可
	private AuthenticationManager authenticationManager;
	private SessionAuthenticationStrategy sessionStrategy;
	protected ApplicationEventPublisher eventPublisher;
	private RememberMeServices rememberMeServices;
	private AuthenticationSuccessHandler successHandler;
	private AuthenticationFailureHandler failureHandler;
	private SecurityContextRepository securityContextRepository;
	...
	private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		...
		try {
			// 模板模式,該方法子類實現(xiàn)
			Authentication authenticationResult = attemptAuthentication(request, response);
			// 1. 	
			this.sessionStrategy.onAuthentication(authenticationResult, request, response);
			// Authentication success
			if (this.continueChainBeforeSuccessfulAuthentication) {
				chain.doFilter(request, response);
			}
			// 成功后續(xù)處理
			successfulAuthentication(request, response, chain, authenticationResult);
		}
		catch (InternalAuthenticationServiceException failed) {
			// 失敗后續(xù)處理
			unsuccessfulAuthentication(request, response, failed);
		}
		catch (AuthenticationException ex) {
			// Authentication failed
			unsuccessfulAuthentication(request, response, ex);
		}
	}
	// 模板模式,由UsernamePasswordAuthenticationFilter完成
	public abstract Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException;}
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
			Authentication authResult) throws IOException, ServletException {
		SecurityContext context = SecurityContextHolder.createEmptyContext();
		context.setAuthentication(authResult);
		// 2. 
		SecurityContextHolder.setContext(context);
		// 3. 
		this.securityContextRepository.saveContext(context, request, response);
		// 4.
		this.rememberMeServices.loginSuccess(request, response, authResult);
		if (this.eventPublisher != null) {
			// 5.
			this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
		}
		// 6.
		this.successHandler.onAuthenticationSuccess(request, response, authResult);
	}
}

UsernamePasswordAuthenticationFilter

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (this.postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		String username = obtainUsername(request);
		username = (username != null) ? username.trim() : "";
		String password = obtainPassword(request);
		password = (password != null) ? password : "";
		UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
				password);
		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);
		// 調(diào)用父類中字段去認證,最終是 UserDetailService#loadUserByUsername(String username),該接口實現(xiàn)類由程序員根據(jù)業(yè)務定義。
		return this.getAuthenticationManager().authenticate(authRequest);
	}
	// ************** 重要 **************
	// 這里只能通過x-www-urlencoded方式獲取,如果前端傳過來application/json,是解析不到的
	// 非要用application/json,建議重寫UsernamePasswordAuthenticationFilter方法,但由于body中內(nèi)容默認只能讀一次,又要做很多其他配置,比較麻煩,建議這里x-www-urlencoded
	// *********************************
	@Nullable
	protected String obtainUsername(HttpServletRequest request) {
		return request.getParameter(this.usernameParameter);
	}
	@Nullable
	protected String obtainPassword(HttpServletRequest request) {
		return request.getParameter(this.passwordParameter);
	}
}

到此這篇關(guān)于Spring Security賬戶與密碼驗證實現(xiàn)過程的文章就介紹到這了,更多相關(guān)Spring Security內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 基于SpringMVC實現(xiàn)網(wǎng)頁登錄攔截

    基于SpringMVC實現(xiàn)網(wǎng)頁登錄攔截

    SpringMVC的處理器攔截器類似于Servlet開發(fā)中的過濾器Filter,用于對處理器進行預處理和后處理。因此,本文將為大家介紹如何通過SpringMVC實現(xiàn)網(wǎng)頁登錄攔截功能,需要的小伙伴可以了解一下
    2021-12-12
  • Junit寫法及與spring整合過程詳解

    Junit寫法及與spring整合過程詳解

    這篇文章主要介紹了Junit寫法及與spring整合過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • SpringBoot中HTTP請求不通的原因級解決方法

    SpringBoot中HTTP請求不通的原因級解決方法

    HTTP 請求是指從客戶端到服務器的請求消息,對于一個 Spring Boot 項目而言,服務器就是 Spring Boot,客戶端就是用戶本地的瀏覽器,但是會遇到SpringBoot HTTP請求不通的問題,本文介紹了一些常見問題及解決方法,需要的朋友可以參考下
    2025-02-02
  • Java中Iterator(迭代器)的用法詳解

    Java中Iterator(迭代器)的用法詳解

    Java迭代器(Iterator)是?Java?集合框架中的一種機制,它提供了一種在不暴露集合內(nèi)部實現(xiàn)的情況下遍歷集合元素的方法。本文主要介紹了它的使用方法,希望對大家有所幫助
    2023-05-05
  • Java 基礎(chǔ)語法中的邏輯控制

    Java 基礎(chǔ)語法中的邏輯控制

    這篇文章主要介紹了Java 基礎(chǔ)語法中的邏輯控制的相關(guān)資料,需要的朋友可以參考下面文章內(nèi)容
    2021-09-09
  • Java多線程處理千萬級數(shù)據(jù)更新操作

    Java多線程處理千萬級數(shù)據(jù)更新操作

    這篇文章主要為大家詳細介紹了Java如何通過多線程處理千萬級數(shù)據(jù)更新操作,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2024-11-11
  • Java中final關(guān)鍵字的深入探究

    Java中final關(guān)鍵字的深入探究

    這篇文章主要給大家介紹了關(guān)于Java中final關(guān)鍵字的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Java具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-06-06
  • Java實現(xiàn)超簡單抖音去水印的示例詳解

    Java實現(xiàn)超簡單抖音去水印的示例詳解

    抖音去水印方法很簡單,以前一直沒有去研究,以為搞個去水印還要用到算法去除,直到動手的時候才發(fā)現(xiàn)這么簡單,不用編程基礎(chǔ)都能做。所以本文將介紹一個超簡單抖音視頻去水印方法,需要的可以參考一下
    2022-03-03
  • Java基礎(chǔ)之Filter的實例詳解

    Java基礎(chǔ)之Filter的實例詳解

    這篇文章主要介紹了Java基礎(chǔ)之Filter的實例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • 一文詳解Java中的AuthRequest類(附Demo)

    一文詳解Java中的AuthRequest類(附Demo)

    公共接口,定義了對第三方平臺進行授權(quán)、登錄、撤銷授權(quán)和刷新 token 的操作,本文將詳細分析Java中的AuthRequest類(附Demo),文中通過代碼示例介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下
    2024-04-04

最新評論

乌鲁木齐市| 鄂托克旗| 金昌市| 沁水县| 凤翔县| 天峨县| 黔东| 金平| 琼海市| 巢湖市| 土默特左旗| 正阳县| 正阳县| 平罗县| 华蓥市| 昆山市| 呼图壁县| 尼玛县| 赤壁市| 通渭县| 宿州市| 南平市| 井研县| 高雄市| 华池县| 清徐县| 昌图县| 栖霞市| 新邵县| 施甸县| 阳朔县| 资兴市| 安徽省| 无为县| 隆尧县| 库车县| 南涧| 云霄县| 盐池县| 涡阳县| 龙陵县|