欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Security中successHandler和failureHandler使用方式

 更新時間:2024年08月01日 15:13:47   作者:放肆熱愛  
這篇文章主要介紹了Spring Security中successHandler和failureHandler使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

前言

successHandler和failureHandler是Spring Security中兩個較為強大的用來處理登錄成功和失敗的回調(diào)函數(shù),通過它們兩個我們就可以自定義一些前后端數(shù)據(jù)的交互。

successHandler

該方法有三個參數(shù)

  • req:相當(dāng)與HttpServletRequest
  • res:相當(dāng)與HttpServletRespose
  • authentication:這里保存了我們登錄后的用戶信息

進(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)與HttpServletRequest
  • res:相當(dāng)與HttpServletRespose
  • e:這里保存了我們登錄失敗的原因

異常種類:

  • 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)與HttpServletRequest
  • res:相當(dāng)與HttpServletRespose
  • authException:指的就是我們未認(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?AOP?的注解

    一篇文章帶你了解Spring?AOP?的注解

    這篇文章主要為大家介紹了vue組件通信的幾種方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-01-01
  • 使用spring實現(xiàn)郵件的發(fā)送實例(含測試,源碼,注釋)

    使用spring實現(xiàn)郵件的發(fā)送實例(含測試,源碼,注釋)

    本篇文章主要介紹了使用spring實現(xiàn)郵件的發(fā)送實例,詳細(xì)的介紹了使用spring配置實現(xiàn)郵件發(fā)送,含測試,源碼,注釋,有興趣的可以下
    2017-05-05
  • 詳解SpringBoot啟動代碼和自動裝配源碼分析

    詳解SpringBoot啟動代碼和自動裝配源碼分析

    這篇文章主要介紹了SpringBoot啟動代碼和自動裝配源碼分析,使用SpringBoot很簡單,在主類中添加一個@SpringBootApplication,以及調(diào)用SpringApplication.run()并傳入主類,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • Springboot調(diào)整接口響應(yīng)返回時長詳解(解決響應(yīng)超時問題)

    Springboot調(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-01
  • 基于Java的電梯系統(tǒng)實現(xiàn)過程

    基于Java的電梯系統(tǒng)實現(xiàn)過程

    這篇文章主要介紹了基于Java的電梯系統(tǒng)實現(xiàn)過程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-10-10
  • SpringBoot集成SwaggerUi以及啟動時遇到的錯誤

    SpringBoot集成SwaggerUi以及啟動時遇到的錯誤

    這篇文章主要介紹了SpringBoot集成SwaggerUi以及啟動時遇到的錯誤,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • SpringBoot使用Flyway進(jìn)行數(shù)據(jù)庫遷移的實現(xiàn)示例

    SpringBoot使用Flyway進(jìn)行數(shù)據(jù)庫遷移的實現(xiàn)示例

    Flyway是一個數(shù)據(jù)庫遷移工具,它提供遷移歷史和回滾的功能,本文主要介紹了如何使用Flyway來管理Spring Boot應(yīng)用程序中的SQL數(shù)據(jù)庫架構(gòu),感興趣的可以了解一下
    2023-08-08
  • Struts中action線程安全問題解析

    Struts中action線程安全問題解析

    這篇文章主要介紹了Struts中action線程安全問題解析,涉及實例代碼,還是挺不錯的,具有一定參考價值,需要的朋友可以了解下。
    2017-10-10
  • springboot清除字符串前后空格與防xss攻擊方法

    springboot清除字符串前后空格與防xss攻擊方法

    這篇文章主要介紹了springboot清除字符串前后空格與防xss攻擊方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 基于XML配置Spring的自動裝配過程解析

    基于XML配置Spring的自動裝配過程解析

    這篇文章主要介紹了基于XML配置Spring的自動裝配過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-10-10

最新評論