溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring security自定義登錄成功后的處理是什么樣的

發(fā)布時間:2021-10-20 17:19:59 來源:億速云 閱讀:212 作者:柒染 欄目:大數(shù)據(jù)

Spring security自定義登錄成功后的處理是什么樣的,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

我們來講一下如何自定義登錄成功后的處理邏輯。先來回顧下默認(rèn)情況下,登錄成功過后spring security 會幫我們做些什么: 未登錄的情況下,我們直接訪問應(yīng)用中的資源,頁面會自動跳轉(zhuǎn)到登錄頁;當(dāng)?shù)卿洺晒螅撁鏁詣又囟ㄏ虻轿业卿浨罢埱蟮?url。

如何更改默認(rèn)的登錄成功后的處理結(jié)果

比如:如果我們想在登錄成功后,響應(yīng)一個 json 字符串(包括“登錄成功”這樣的提示信息,響應(yīng)code,以及跳轉(zhuǎn)的url)給前端。應(yīng)該怎么辦?

步驟 1

首先復(fù)制上一節(jié)的項(xiàng)目工程 spring-security-02,重命名為 Spring-security-03。 maven 依賴不需要改變,如下所示:

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

	</dependencies>

步驟2

定義登錄成功后的處理類 GoAuthenticationSuccessHandler

	/**
	 * 自定義 登錄成功 處理類
	 */
	[@Component](https://my.oschina.net/u/3907912)
	public class GoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

		@Autowired
		private ObjectMapper objectMapper;

		/**
		 * {"code":200,"message":"操作成功","data":"登錄成功"}
		 * [@param](https://my.oschina.net/u/2303379) request
		 * [@param](https://my.oschina.net/u/2303379) response
		 * [@param](https://my.oschina.net/u/2303379) authentication
		 * @throws IOException
		 * @throws ServletException
		 */
		@Override
		public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
				throws IOException, ServletException {
			response.setHeader("Content-Type", "application/json;charset=utf-8");
			response.getWriter().print(objectMapper.writeValueAsString(CommonResult.success("登錄成功")));
			response.getWriter().flush();
		}
	}

步驟2

在 WebSecurityConfig 配置類中,注入自定義處理類的依賴 :

@Autowired
private GoAuthenticationSuccessHandler successHandler;
@Autowired
private GoAuthenticationFailureHandler failureHandler;

步驟3

在 protected void configure(HttpSecurity http) 方法中,追加如下代碼:

	// 這些是本來就有的
	http.formLogin()
	.loginPage("/loginPage.html")// 自定義登錄頁
	.loginProcessingUrl("/form/login")// 自定義登錄 action, 名字隨便起
	// 以下是新增的
	.successHandler(successHandler)// 自定義登錄成功處理類
	.failureHandler(failureHandler);// 自定義登錄失敗處理類

小結(jié)

從上面的代碼中我們可以看到,新增了兩個配置,在 successHandler 和 failureHandler 方法中分別注入了一個處理類,我們著重看下 GoAuthenticationSuccessHandler 處理類, 通過重寫 AuthenticationSuccessHandler 的方法,響應(yīng)了一段json給前端。 而failureHandler 是登錄失敗時做一些處理,在這里我們會響應(yīng)登錄失敗的message給前端。這些響應(yīng)結(jié)果我們都可以自定義。 你可以根據(jù)實(shí)際需求去選擇是否需要自定義這些處理類。

擴(kuò)展

回顧一下,之前如果用戶沒有登錄直接訪問我們的應(yīng)用資源,會自動跳轉(zhuǎn)到登錄頁,如果登錄成功后,去訪問沒有權(quán)限的url,會給我們一段英文提示,大致意思就是沒有權(quán)限。這些我們?nèi)匀皇强梢远ㄖ频摹1热绠?dāng)我們沒有登錄時,給前端提示“用戶未登錄”,當(dāng)我們沒有權(quán)限時,提示前端“用戶沒有權(quán)限”。

步驟1

定義兩個處理類 GoAuthenticationEntryPoint 和 GoAccessDeniedHandler

`

/**
 * 自定義 未登錄 或者 token 失效 處理類
 */
@Component
public class GoAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Autowired
	private ObjectMapper objectMapper;

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.getWriter().println(objectMapper.writeValueAsString(CommonResult.unauthorized(authException.getMessage())));
		response.getWriter().flush();
	}
}

/**
 * 自定義沒有訪問權(quán)限處理類
 */
@Component
public class GoAccessDeniedHandler implements AccessDeniedHandler {

	@Autowired
	private ObjectMapper objectMapper;

	/**
	 * @param request
	 * @param response
	 * @param e
	 * @throws IOException
	 * @throws ServletException
	 *
	 * @return {"code":403,"message":"沒有相關(guān)權(quán)限","data":"Access is denied"}
	 */
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
		response.setHeader("Content-Type", "application/json;charset=utf-8");
		response.getWriter().print(objectMapper.writeValueAsString(CommonResult.forbidden(e.getMessage())));
		response.getWriter().flush();
	}
}

`

步驟2

將自定義的兩個處理類注入到 WebSecurityConfig 類中

` @Autowired private GoAccessDeniedHandler accessDeniedHandler;

@Autowired
private GoAuthenticationEntryPoint entryPoint;

`

步驟3

打開 WebSecurityConfig 配置類,在 configure 方法中追加如下代碼:

@Override protected void configure(HttpSecurity http) throws Exception { // 此處省略一部分代碼 http.exceptionHandling() .accessDeniedHandler(accessDeniedHandler)// 用戶沒有訪問權(quán)限處理器 .authenticationEntryPoint(entryPoint);// 用戶沒有登錄處理器 }

上面我們總共定義了四個處理類,分別作用于以下四種情況發(fā)生之后:

  1. 當(dāng)我們登錄成功后。

  2. 當(dāng)我們登錄失敗后。

  3. 當(dāng)我們沒有登錄而去訪問資源時。

  4. 當(dāng)我們訪問沒有權(quán)限的資源時。

看完上述內(nèi)容,你們掌握Spring security自定義登錄成功后的處理是什么樣的的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI