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

SpringSecurity6.x多種登錄方式配置小結(jié)

 更新時(shí)間:2023年12月29日 10:29:15   作者:泉城打碼師  
SpringSecurity6.x變了很多寫法,本文就來介紹一下SpringSecurity6.x多種登錄方式配置小結(jié),具有一定的參考價(jià)值,感興趣的可以了解一下

SpringSecurity6.x變了很多寫法。

在編寫多種登錄方式的時(shí)候,網(wǎng)上大多是5.x的,很多類都沒了。

以下是SpringSecurity6.x多種登錄方式的寫法。

1. 編寫第一種登錄-賬號(hào)密碼json登錄方式

package com.hw.mo.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hw.mo.captcha.config.CaptchaConfig;
import com.hw.mo.security.entity.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;

/**
 * @author : guanzheng
 * @date : 2023/6/26 15:17
 */
public class JsonLoginFilter extends UsernamePasswordAuthenticationFilter {

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String contentType = request.getContentType();

        if (MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(contentType) || MediaType.APPLICATION_JSON_UTF8_VALUE.equalsIgnoreCase(contentType)) {
            if (!request.getMethod().equals("POST")) {
                throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
            }
            String username = null;
            String password = null;
            try {
                LoginUser user = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
                username = user.getUsername();
                username = (username != null) ? username.trim() : "";
                password = user.getPassword();
                password = (password != null) ? password : "";
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request,response);
    }

}

2. 編寫第二種登錄方式-手機(jī)驗(yàn)證碼登錄

package com.hw.mo.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hw.mo.security.domain.PhoneCodeLoginAuthticationToken;
import com.hw.mo.security.entity.LoginUser;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;

public class PhoneCodeLoginFilter extends AbstractAuthenticationProcessingFilter {
    public PhoneCodeLoginFilter() {
        super(new AntPathRequestMatcher("/loginPhoneCode","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        // 需要是 POST 請(qǐng)求
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 判斷請(qǐng)求格式是否 JSON
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            LoginUser user = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
            // 獲得請(qǐng)求參數(shù)
            String username = user.getUsername();
            String phoneCode = user.getPhoneCode();
            String captchaUuid = user.getCaptchaUuid();
            //TODO  檢查驗(yàn)證碼是否正確
            if (CaptchaUtil.validate(captchaUuid,phoneCode).isOk()){
    
            }
            /**
             * 使用請(qǐng)求參數(shù)傳遞的郵箱和驗(yàn)證碼,封裝為一個(gè)未認(rèn)證 EmailVerificationCodeAuthenticationToken 身份認(rèn)證對(duì)象,
             * 然后將該對(duì)象交給 AuthenticationManager 進(jìn)行認(rèn)證
             */
            PhoneCodeLoginAuthticationToken token = new PhoneCodeLoginAuthticationToken(username);
            setDetails(request, token);
            return this.getAuthenticationManager().authenticate(token);
        }
        return null;
    }

    public void setDetails(HttpServletRequest request , PhoneCodeLoginAuthticationToken token){
        token.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
}

3. 編寫驗(yàn)證碼登錄處理器 

package com.hw.mo.security.provider;

import com.hw.mo.security.domain.PhoneCodeLoginAuthticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class PhoneCodeLoginProvider implements AuthenticationProvider {

    UserDetailsService userDetailsService;

    public PhoneCodeLoginProvider(UserDetailsService userDetailsService){
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication.isAuthenticated()) {
            return authentication;
        }
        //獲取過濾器封裝的token信息
        PhoneCodeLoginAuthticationToken authenticationToken = (PhoneCodeLoginAuthticationToken) authentication;
        String username = (String)authenticationToken.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

//        不通過
        if (userDetails == null) {
            throw new BadCredentialsException("用戶不存在");
        }
        // 根用戶擁有全部的權(quán)限

        PhoneCodeLoginAuthticationToken authenticationResult = new PhoneCodeLoginAuthticationToken(userDetails, null);

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return PhoneCodeLoginAuthticationToken.class.isAssignableFrom(authentication);
    }
}

4. 配置SecurityConfiguration,把上邊的兩個(gè) 登錄過濾器加到過濾器鏈中。

package com.hw.mo.security.config;

import com.hw.mo.security.filter.JsonLoginFilter;
import com.hw.mo.security.filter.JwtAuthenticationFilter;
import com.hw.mo.security.filter.PhoneCodeLoginFilter;
import com.hw.mo.security.handler.*;
import com.hw.mo.security.provider.PhoneCodeLoginProvider;
import com.hw.mo.security.service.impl.LoginUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author : guanzheng
 * @date : 2023/6/25 9:03
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Autowired
    LoginUserDetailServiceImpl userDetailService;
    @Autowired
    MoPasswordEncoder passwordEncoder;
    @Autowired
    PhoneCodeLoginProvider phoneCodeLoginProvider;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize)->
                    authorize
                            .requestMatchers("/rongyan/**","/login*","/captcha*","/register*").permitAll()
                            .anyRequest().authenticated()
                )
                .addFilterBefore(new JwtAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class)

                .exceptionHandling(e-> {
                    e.accessDeniedHandler(new MyAccessDeniedHandler());
                    e.authenticationEntryPoint(new AuthenticatedErrorHandler());
                })

                .csrf(csrf -> csrf.disable())
                .cors(cors -> cors.disable())
                ;
        return http.build();
    }

    /**
     * 加載賬號(hào)密碼json登錄
     */
    @Bean
    JsonLoginFilter myJsonLoginFilter(HttpSecurity http) throws Exception {
        JsonLoginFilter myJsonLoginFilter = new JsonLoginFilter();
        //自定義登錄url
        myJsonLoginFilter.setFilterProcessesUrl("/login");
        myJsonLoginFilter.setAuthenticationSuccessHandler(new LoginSuccessHandler());
        myJsonLoginFilter.setAuthenticationFailureHandler(new LoginFailureHandler());
        myJsonLoginFilter.setAuthenticationManager(authenticationManager(http));
        return myJsonLoginFilter;
    }

    /**
     * 加載手機(jī)驗(yàn)證碼登錄
     */
    @Bean
    PhoneCodeLoginFilter phoneCodeLoginFilter(HttpSecurity http) throws Exception {
        PhoneCodeLoginFilter phoneCodeLoginFilter = new PhoneCodeLoginFilter();
        //自定義登錄url
        phoneCodeLoginFilter.setFilterProcessesUrl("/loginPhoneCode");
        phoneCodeLoginFilter.setAuthenticationSuccessHandler(new LoginSuccessHandler());
        phoneCodeLoginFilter.setAuthenticationFailureHandler(new LoginFailureHandler());
        phoneCodeLoginFilter.setAuthenticationManager(authenticationManager(http));
        return phoneCodeLoginFilter;
    }


    @Bean
    AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        //設(shè)置用戶信息處理器
        daoAuthenticationProvider.setUserDetailsService(userDetailService);
        //設(shè)置密碼處理器
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);

        AuthenticationManagerBuilder authenticationManagerBuilder =
                http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.authenticationProvider(phoneCodeLoginProvider);//自定義的
        authenticationManagerBuilder.authenticationProvider(daoAuthenticationProvider);//原來默認(rèn)的

        return authenticationManagerBuilder.build();
    }

}

 到此這篇關(guān)于SpringSecurity6.x多種登錄方式配置小結(jié)的文章就介紹到這了,更多相關(guān)SpringSecurity6.x 登錄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 探索Java中的IP屬地獲取技術(shù)

    探索Java中的IP屬地獲取技術(shù)

    這篇文章主要為大家介紹了Java中的IP屬地獲取的技術(shù)探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10
  • Spring Boot從Controller層進(jìn)行單元測(cè)試的實(shí)現(xiàn)

    Spring Boot從Controller層進(jìn)行單元測(cè)試的實(shí)現(xiàn)

    這篇文章主要介紹了Spring Boot從Controller層進(jìn)行單元測(cè)試的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • 基于idea操作hbase數(shù)據(jù)庫(kù)并映射到hive表

    基于idea操作hbase數(shù)據(jù)庫(kù)并映射到hive表

    這篇文章主要介紹了用idea操作hbase數(shù)據(jù)庫(kù),并映射到hive,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-03-03
  • Spring中@Import的各種用法以及ImportAware接口詳解

    Spring中@Import的各種用法以及ImportAware接口詳解

    這篇文章主要介紹了Spring中@Import的各種用法以及ImportAware接口詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • java獲取客服端信息的方法(系統(tǒng),瀏覽器等)

    java獲取客服端信息的方法(系統(tǒng),瀏覽器等)

    下面小編就為大家?guī)硪黄猨ava獲取客服端信息的方法(系統(tǒng),瀏覽器等)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-09-09
  • GraalVm的反射配置輔助工具agentlib配置及使用

    GraalVm的反射配置輔助工具agentlib配置及使用

    這篇文章主要為大家介紹了GraalVm的反射配置輔助工具agentlib的配置文件及使用說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2022-02-02
  • Java純代碼實(shí)現(xiàn)導(dǎo)出PDF功能

    Java純代碼實(shí)現(xiàn)導(dǎo)出PDF功能

    在項(xiàng)目開發(fā)中,產(chǎn)品的需求越來越奇葩啦,開始文件下載都是下載為excel的,做著做著需求竟然變了,要求能導(dǎo)出pdf,本文就來和大家分享一下Java實(shí)現(xiàn)導(dǎo)出PDF的常用方法吧
    2023-07-07
  • Java實(shí)現(xiàn)獲取內(nèi)網(wǎng)的所有IP地址

    Java實(shí)現(xiàn)獲取內(nèi)網(wǎng)的所有IP地址

    這篇文章主要介紹了如何利用Java語(yǔ)言實(shí)現(xiàn)獲取內(nèi)網(wǎng)的所有IP地址,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)有一定的參考價(jià)值,快跟隨小編一起學(xué)習(xí)一下吧
    2022-06-06
  • SpringBoot+RabbitMQ+Redis實(shí)現(xiàn)商品秒殺的示例代碼

    SpringBoot+RabbitMQ+Redis實(shí)現(xiàn)商品秒殺的示例代碼

    本文主要介紹了SpringBoot+RabbitMQ+Redis實(shí)現(xiàn)商品秒殺,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • java獲得mysql和oracle鏈接的類

    java獲得mysql和oracle鏈接的類

    這篇文章主要介紹了java獲得mysql和oracle鏈接的類,可實(shí)現(xiàn)基于jdbc的mysql與oracle數(shù)據(jù)庫(kù)連接,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-07-07

最新評(píng)論