最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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. 編寫第一種登錄-賬號密碼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 請求
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 判斷請求格式是否 JSON
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            LoginUser user = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
            // 獲得請求參數(shù)
            String username = user.getUsername();
            String phoneCode = user.getPhoneCode();
            String captchaUuid = user.getCaptchaUuid();
            //TODO  檢查驗(yàn)證碼是否正確
            if (CaptchaUtil.validate(captchaUuid,phoneCode).isOk()){
    
            }
            /**
             * 使用請求參數(shù)傳遞的郵箱和驗(yàn)證碼,封裝為一個(gè)未認(rèn)證 EmailVerificationCodeAuthenticationToken 身份認(rèn)證對象,
             * 然后將該對象交給 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();
    }

    /**
     * 加載賬號密碼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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 在springboot中使用AOP進(jìn)行全局日志記錄

    在springboot中使用AOP進(jìn)行全局日志記錄

    這篇文章主要介紹就在springboot中使用AOP進(jìn)行全局日志記錄,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • mybatis-plus無法通過logback-spring輸出的解決方法

    mybatis-plus無法通過logback-spring輸出的解決方法

    本文主要介紹了mybatis-plus無法通過logback-spring輸出,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Java?函數(shù)式編程梳理

    Java?函數(shù)式編程梳理

    這篇文章主要介紹了Java?函數(shù)式編程梳理,文章通過Lambda表達(dá)式展開詳細(xì)的內(nèi)容介紹,具有一定參考價(jià)值,需要的小伙伴可以參考一下
    2022-07-07
  • 詳解Java數(shù)字簽名提供XML安全

    詳解Java數(shù)字簽名提供XML安全

    在本篇文章中我們給大家整理了關(guān)于Java數(shù)字簽名提供XML安全的知識點(diǎn)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
    2018-08-08
  • Java使用新浪微博API開發(fā)微博應(yīng)用的基本方法

    Java使用新浪微博API開發(fā)微博應(yīng)用的基本方法

    這篇文章主要介紹了Java使用新浪微博API開發(fā)微博應(yīng)用的基本方法,文中還給出了一個(gè)不使用任何SDK實(shí)現(xiàn)Oauth授權(quán)并實(shí)現(xiàn)簡單的發(fā)布微博功能的實(shí)現(xiàn)方法,需要的朋友可以參考下
    2015-11-11
  • linux用java -jar啟動(dòng)jar包緩慢的問題

    linux用java -jar啟動(dòng)jar包緩慢的問題

    這篇文章主要介紹了linux用java -jar啟動(dòng)jar包緩慢的問題,具有很好的參考價(jià)值,希望對大家有所幫助,
    2023-09-09
  • Mybatis調(diào)用MySQL存儲(chǔ)過程的簡單實(shí)現(xiàn)

    Mybatis調(diào)用MySQL存儲(chǔ)過程的簡單實(shí)現(xiàn)

    本篇文章主要介紹了Mybatis調(diào)用MySQL存儲(chǔ)過程的簡單實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2017-04-04
  • 深入解析Mybatis中緩存機(jī)制及優(yōu)缺點(diǎn)

    深入解析Mybatis中緩存機(jī)制及優(yōu)缺點(diǎn)

    MyBatis緩存分為一級(SqlSession級,自動(dòng)維護(hù))和二級(Mapper級,需配置),通過減少數(shù)據(jù)庫訪問提升性能,但存在臟數(shù)據(jù)和分布式不兼容風(fēng)險(xiǎn),適合高頻查詢低頻修改場景,需合理配置以平衡效率與一致性,本文給介紹Mybatis中緩存機(jī)制及優(yōu)缺點(diǎn),感興趣的朋友跟隨小編一起看看吧
    2025-08-08
  • SpringBoot集成內(nèi)存數(shù)據(jù)庫Sqlite的實(shí)踐

    SpringBoot集成內(nèi)存數(shù)據(jù)庫Sqlite的實(shí)踐

    sqlite這樣的內(nèi)存數(shù)據(jù)庫,小巧可愛,做小型服務(wù)端演示程序,非常好用,本文主要介紹了SpringBoot集成Sqlite,具有一定的參考價(jià)值,感興趣的可以了解一下
    2021-09-09
  • Java中instanceof關(guān)鍵字實(shí)例講解

    Java中instanceof關(guān)鍵字實(shí)例講解

    大家好,本篇文章主要講的是Java中instanceof關(guān)鍵字實(shí)例講解,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-01-01

最新評論

长子县| 镶黄旗| 克山县| 边坝县| 绩溪县| 盘锦市| 格尔木市| 嘉峪关市| 金沙县| 利川市| 崇左市| 琼海市| 浦江县| 汉中市| 灵川县| 湖州市| 尼玛县| 南靖县| 阿克苏市| 金乡县| 永川市| 灯塔市| 遂宁市| 富顺县| 天气| 荣成市| 保定市| 襄樊市| 宁波市| 岑巩县| 霍州市| 登封市| 周至县| 通辽市| 万安县| 乳源| 长兴县| 五华县| 凯里市| 秦安县| 中卫市|