Spring Security中successHandler和failureHandler使用方式
前言
successHandler和failureHandler是Spring Security中兩個較為強大的用來處理登錄成功和失敗的回調(diào)函數(shù),通過它們兩個我們就可以自定義一些前后端數(shù)據(jù)的交互。
successHandler
該方法有三個參數(shù)
req
:相當(dāng)與HttpServletRequestres
:相當(dāng)與HttpServletResposeauthentication
:這里保存了我們登錄后的用戶信息
進(jìn)行如下配置
.successHandler((req, resp, authentication) -> { Object principal = authentication.getPrincipal(); resp.setContentType("application/json;charset=utf-8"); PrintWriter out = resp.getWriter(); out.write(new ObjectMapper().writeValueAsString(principal)); out.flush(); out.close(); })
配置類代碼
package com.scexample.sc.config; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import java.io.PrintWriter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("xiaoming") .password("123456").roles("admin"); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/js/**","/css/**","/images/**"); //這個是用來忽略一些url地址,對其不進(jìn)行校驗,通常用在一些靜態(tài)文件中。 } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/aaa.html") .loginProcessingUrl("/logintest") .usernameParameter("name") .passwordParameter("passwd") .successHandler((req, res, authentication) -> { Object principal = authentication.getPrincipal(); res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write(new ObjectMapper().writeValueAsString(principal)); out.flush(); out.close(); }) .permitAll() .and() .csrf().disable() ); } }
再次登錄后
failureHandler
該方法有三個參數(shù)
req
:相當(dāng)與HttpServletRequestres
:相當(dāng)與HttpServletResposee
:這里保存了我們登錄失敗的原因
異常種類:
LockedException
賬戶鎖定CredentialsExpiredException
密碼過期AccountExpiredException
賬戶過期DisabledException
賬戶被禁止BadCredentialsException
用戶名或者密碼錯誤
.failureHandler((req, res, e) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write(e.getMessage()); out.flush(); out.close(); })
配置類代碼:
package com.scexample.sc.config; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import java.io.PrintWriter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("xiaoming") .password("123456").roles("admin"); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/js/**","/css/**","/images/**"); //這個是用來忽略一些url地址,對其不進(jìn)行校驗,通常用在一些靜態(tài)文件中。 } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/aaa.html") .loginProcessingUrl("/logintest") .usernameParameter("name") .passwordParameter("passwd") .successHandler((req, res, authentication) -> { Object principal = authentication.getPrincipal(); res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write(new ObjectMapper().writeValueAsString(principal)); out.flush(); out.close(); }) .failureHandler((req, res, e) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write(e.getMessage()); out.flush(); out.close(); }) .permitAll() .and() .csrf().disable() } }
未認(rèn)證處理方法
spring security默認(rèn)情況下,如果認(rèn)證不成功,直接重定向到登錄頁面。
但是項目中,我們有的時候不需要這樣,我們需要在前端進(jìn)行判斷 ,然后再決定進(jìn)行其他的處理,那我們就可以用authenticationEntryPoint這個接口進(jìn)行自定義了,取消它的默認(rèn)重定向行為。
該方法有三個參數(shù)
req
:相當(dāng)與HttpServletRequestres
:相當(dāng)與HttpServletResposeauthException
:指的就是我們未認(rèn)證的exception
.csrf().disable() .exceptionHandling() .authenticationEntryPoint((req, res, authException) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write("檢測到未登錄狀態(tài),請先登錄"); out.flush(); out.close(); }
配置類代碼
package com.scexample.sc.config; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import java.io.PrintWriter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("xiaoming") .password("123456").roles("admin"); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/js/**","/css/**","/images/**"); //這個是用來忽略一些url地址,對其不進(jìn)行校驗,通常用在一些靜態(tài)文件中。 } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/aaa.html") .loginProcessingUrl("/logintest") .usernameParameter("name") .passwordParameter("passwd") .successHandler((req, res, authentication) -> { Object principal = authentication.getPrincipal(); res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write(new ObjectMapper().writeValueAsString(principal)); out.flush(); out.close(); }) .failureHandler((req, res, e) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write(e.getMessage()); out.flush(); out.close(); }) .permitAll() .and() .csrf().disable() .exceptionHandling() .authenticationEntryPoint((req, res, authException) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write("檢測到未登錄狀態(tài),請先登錄"); out.flush(); out.close(); } ); } }
注銷登錄
.logoutSuccessHandler((req, res, authentication) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write("注銷成功"); out.flush(); out.close(); })
配置類代碼:
package com.scexample.sc.config; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import java.io.PrintWriter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("xiaoming") .password("123456").roles("admin"); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/js/**","/css/**","/images/**"); //這個是用來忽略一些url地址,對其不進(jìn)行校驗,通常用在一些靜態(tài)文件中。 } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/aaa.html") .loginProcessingUrl("/logintest") .usernameParameter("name") .passwordParameter("passwd") .successHandler((req, res, authentication) -> { Object principal = authentication.getPrincipal(); res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write(new ObjectMapper().writeValueAsString(principal)); out.flush(); out.close(); }) .failureHandler((req, res, e) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write(e.getMessage()); out.flush(); out.close(); }) .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessHandler((req, res, authentication) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write("注銷成功"); out.flush(); out.close(); }) .permitAll() .and() .csrf().disable() .exceptionHandling() .authenticationEntryPoint((req, res, authException) -> { res.setContentType("application/json;charset=utf-8"); PrintWriter out = res.getWriter(); out.write("檢測到未登錄狀態(tài),請先登錄"); out.flush(); out.close(); } ); } }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用spring實現(xiàn)郵件的發(fā)送實例(含測試,源碼,注釋)
本篇文章主要介紹了使用spring實現(xiàn)郵件的發(fā)送實例,詳細(xì)的介紹了使用spring配置實現(xiàn)郵件發(fā)送,含測試,源碼,注釋,有興趣的可以下2017-05-05Springboot調(diào)整接口響應(yīng)返回時長詳解(解決響應(yīng)超時問題)
當(dāng)后端對于數(shù)據(jù)量較大的處理或是某些耗時的操作時,需要先對請求接口的請求進(jìn)行響應(yīng),下面這篇文章主要給大家介紹了關(guān)于Springboot調(diào)整接口響應(yīng)返回時長(解決響應(yīng)超時問題)的相關(guān)資料,需要的朋友可以參考下2023-01-01SpringBoot集成SwaggerUi以及啟動時遇到的錯誤
這篇文章主要介紹了SpringBoot集成SwaggerUi以及啟動時遇到的錯誤,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06SpringBoot使用Flyway進(jìn)行數(shù)據(jù)庫遷移的實現(xiàn)示例
Flyway是一個數(shù)據(jù)庫遷移工具,它提供遷移歷史和回滾的功能,本文主要介紹了如何使用Flyway來管理Spring Boot應(yīng)用程序中的SQL數(shù)據(jù)庫架構(gòu),感興趣的可以了解一下2023-08-08