亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Spring security自定義用戶認證流程詳解

瀏覽:40日期:2023-09-16 18:44:46

1.自定義登錄頁面

(1)首先在static目錄下面創建login.html

  注意:springboot項目默認可以訪問resources/resources,resources/staic,resources/public目錄下面的靜態文件

<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>登錄頁面</title></head><body><form action='/auth/login' method='post'> 用戶名:<input type='text' name='username'> <br/> 密&emsp;碼:<input type='password' name='password'> <br/> <input type='submit' value='登錄'></form></body></html>

(2)在spring securiy配置類中做如下配置

@Override protected void configure(HttpSecurity http) throws Exception { http.formLogin()// 指定自定義登錄頁面.loginPage('/login.html')// 登錄url.loginProcessingUrl('/auth/login').and().authorizeRequests()// 添加一個url匹配器,如果匹配到login.html,就授權.antMatchers('/login.html').permitAll().anyRequest().authenticated().and()// 關閉spring security默認的防csrf攻擊.csrf().disable(); }

(3)測試

(4)存在的問題

<1>作為可以復用的登錄模塊,我們應該提供個性化的登錄頁面,也就是說不能寫死只跳轉到login.html。

此問題比較好解決,使用可配置的登錄頁面,默認使用login.html即可。

<2> 請求跳轉到login.html登錄頁面,貌似沒有什么問題,但作為restful風格的接口,一般響應的都是json數據格式,尤其是app請求。

解決思想:用戶發起數據請求 --> security判斷是否需要身份認證 ----->跳轉到一個自定義的controller方法 ------>在該方法內判斷是否是html發起的請求,如果是,就跳轉到login.html,如果不是,響應一個json格式的數據,說明錯誤信息。

自定義Controller

@Slf4j@RestControllerpublic class LoginController { /** * 請求緩存 */ private RequestCache requestCache = new HttpSessionRequestCache(); /** * 重定向工具類 */ private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); /** * 如果配置的登錄頁就使用配置的登錄面,否則使用默認的登錄頁面 */// @Value('${xxxx:defaultLoginPage}')// private String standardLoginPage; private String standardLoginPage = '/login.html'; // 登錄頁 /** * 用戶身份認證方法 */ @GetMapping('/user/auth') @ResponseStatus(code = HttpStatus.UNAUTHORIZED) // 返回狀態 public ResponseData login(HttpServletRequest request, HttpServletResponse response) throws IOException { SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest != null) { String targetUrl = savedRequest.getRedirectUrl(); log.info('請求是:' + targetUrl); // 如果請求是以html結尾 if (StringUtils.endsWithIgnoreCase(targetUrl, '.html')) {redirectStrategy.sendRedirect(request, response, standardLoginPage); } } return new ResponseData('該請求需要登錄,js拿到我的響應數據后,是否需要跳轉到登錄頁面你自己看著辦吧?'); }}

spring security給該controller的login方法授權

@Override protected void configure(HttpSecurity http) throws Exception { http.formLogin()// 先進controller中去.loginPage('/user/auth')// 指定自定義登錄頁面.loginPage('/login.html')// 登錄url.loginProcessingUrl('/auth/login').and().authorizeRequests()// 該controller需要授權.antMatchers('/user/auth').permitAll()// 添加一個url匹配器,如果匹配到login.html,就授權.antMatchers('/login.html').permitAll().anyRequest().authenticated().and()// 關閉spring security默認的防csrf攻擊.csrf().disable(); }

這樣子就行了!!! 

2. 自定義登錄成功處理(返回json)

(1)實現AuthenticationSuccessHandler.java

import com.fasterxml.jackson.databind.ObjectMapper;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;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;@Slf4j@Componentpublic class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Autowired private ObjectMapper objectMapper; /** * Called when a user has been successfully authenticated. * @param request * @param response * @param authentication * @throws IOException * @throws ServletException */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { log.info('登錄成功!!!'); // 將登錄成功的信息寫到前端 response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write(objectMapper.writeValueAsString(authentication)); }}

(2)修改security配置類

@Autowired private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin()// 先進controller中去.loginPage('/user/auth')// 指定自定義登錄頁面.loginPage('/login.html')// 登錄url.loginProcessingUrl('/auth/login').successHandler(myAuthenticationSuccessHandler).and().authorizeRequests()// 該controller需要授權.antMatchers('/user/auth').permitAll()// 添加一個url匹配器,如果匹配到login.html,就授權.antMatchers('/login.html').permitAll().anyRequest().authenticated().and()// 關閉spring security默認的防csrf攻擊.csrf().disable(); }

(3)測試

Spring security自定義用戶認證流程詳解

說明:authentication對象中包含的信息,會因為登錄方式的不同而發生改變

3.自定義登錄失敗處理(返回json)

實現AuthenticationFailureHandler.java接口即可,跟登錄成敗處理配置一樣。

4.自定義登錄成功處理邏輯

 以上的登錄成功或失敗的返回的都是json,但是在某些情況下,就是存在著登錄成功或者失敗進行頁面跳轉(spring security默認的處理方式),那么這種返回json的方式就不合適了。所以,我們應該做得更靈活,做成可配置的。

 對于登錄成功邏輯而言只需要對MyAuthenticationSuccessHandler.java稍做修改就行,代碼如下所示:

/** * SavedRequestAwareAuthenticationSuccessHandler spring security 默認的成功處理器 */@Slf4j@Componentpublic class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Autowired private ObjectMapper objectMapper; /** * 配置的登錄方式 */// @Value('${xxx:默認方式}') private String loginType = 'JSON'; /** * Called when a user has been successfully authenticated. */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { log.info('登錄成功!!!'); // 如果配置的登錄方式是JSON,就返回json數據 if ('JSON'.equals(loginType)) { // 將登錄成功的信息寫到前端 response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write(objectMapper.writeValueAsString(authentication)); } else { // 否則就使用默認的跳轉方式 super.onAuthenticationSuccess(request,response,authentication); } }}

5.自定義登錄失敗處理邏輯

同登錄成功類似,具體代碼如下:

import com.fasterxml.jackson.databind.ObjectMapper;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@Slf4j@Componentpublic class MySimpleUrlAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Autowired private ObjectMapper objectMapper; /** * 配置的登錄方式 */// @Value('${xxx:默認方式}') private String loginType = 'JSON'; @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { log.info('登錄失敗!!!'); // 如果配置的登錄方式是JSON,就返回json數據 if ('JSON'.equals(loginType)) { // 將登錄成功的信息寫到前端 response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write(objectMapper.writeValueAsString(exception)); } else { // 否則就使用默認的跳轉方式,跳轉到一個錯誤頁面 super.onAuthenticationFailure(request,response,exception); } }}

@Autowired private MySimpleUrlAuthenticationFailureHandler mySimpleUrlAuthenticationFailureHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin()// 先進controller中去.loginPage('/user/auth')// 指定自定義登錄頁面.loginPage('/login.html')// 登錄url.loginProcessingUrl('/auth/login').successHandler(myAuthenticationSuccessHandler).failureHandler(mySimpleUrlAuthenticationFailureHandler).and().authorizeRequests()// 該controller需要授權.antMatchers('/user/auth').permitAll()// 添加一個url匹配器,如果匹配到login.html,就授權.antMatchers('/login.html').permitAll().anyRequest().authenticated().and()// 關閉spring security默認的防csrf攻擊.csrf().disable(); }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 亚洲精品成人网 | 中文字幕第一页亚洲 | 欧美成人香蕉网在线观看 | 天堂久久久久va久久久久 | 中文字幕欧美日韩一 | 国产成人精品久久亚洲高清不卡 | 在线播放国产一区 | 91在线一区二区三区 | 在线视频免费观看短视频 | 精品热线九九精品视频 | 黄色片毛片 | 特级片在线观看 | 1000部国产成人免费视频 | 欧美日韩综合一区 | 久青草视频在线 | 青草娱乐极品免费视频 | 久久亚洲在线 | 亚洲自偷 | 她也啪97在线视频 | 原味小视频在线www国产 | 中国女人真人一级毛片 | 成人在线精品 | 免费看的毛片 | 国产精品成人免费视频不卡 | 四川丰满护士毛茸茸 | 日本无吗中文字幕免费婷婷 | 青青热久免费精品视频在首页 | 模特尤妮丝凹凸福利视频 | 欧美在线视频一区二区三区 | 国产片一区二区三区 | 久久在线视频播放 | 国产精品臀控福利在线观看 | x8x8国产在线观看2021 | 99视频精品全部免费免费观 | 亚洲欧美日韩在线观看二区 | 国产成人一区在线播放 | 国产一级黄色大片 | 韩国xxxx色视频免费 | 亚洲欧美在线中文字幕不卡 | 爽爽爽爽爽爽a成人免费视频 | 特级做a爰片毛片免费看一区 |