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

SpringSecurity6.x多種登錄方式配置小結

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

SpringSecurity6.x變了很多寫法。

在編寫多種登錄方式的時候,網(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. 編寫第二種登錄方式-手機驗證碼登錄

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  檢查驗證碼是否正確
            if (CaptchaUtil.validate(captchaUuid,phoneCode).isOk()){
    
            }
            /**
             * 使用請求參數(shù)傳遞的郵箱和驗證碼,封裝為一個未認證 EmailVerificationCodeAuthenticationToken 身份認證對象,
             * 然后將該對象交給 AuthenticationManager 進行認證
             */
            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. 編寫驗證碼登錄處理器 

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("用戶不存在");
        }
        // 根用戶擁有全部的權限

        PhoneCodeLoginAuthticationToken authenticationResult = new PhoneCodeLoginAuthticationToken(userDetails, null);

        return authenticationResult;
    }

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

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

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;
    }

    /**
     * 加載手機驗證碼登錄
     */
    @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();
        //設置用戶信息處理器
        daoAuthenticationProvider.setUserDetailsService(userDetailService);
        //設置密碼處理器
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);

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

        return authenticationManagerBuilder.build();
    }

}

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

相關文章

  • 在springboot中使用AOP進行全局日志記錄

    在springboot中使用AOP進行全局日志記錄

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

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

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

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

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

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

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

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

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

    linux用java -jar啟動jar包緩慢的問題

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

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

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

    深入解析Mybatis中緩存機制及優(yōu)缺點

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

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

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

    Java中instanceof關鍵字實例講解

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

最新評論

波密县| 青浦区| 贵州省| 都江堰市| 邹平县| 抚顺市| 洛浦县| 大冶市| 米脂县| 长岭县| 娄烦县| 遂川县| 宜州市| 晋江市| 嘉祥县| 宽城| 玛多县| 哈尔滨市| 宜章县| 济南市| 孟连| 翁源县| 沽源县| 佛冈县| 陇川县| 合作市| 富源县| 绍兴县| 东方市| 石屏县| 黔西县| 隆德县| 嘉鱼县| 东光县| 青河县| 明水县| 呈贡县| 崇阳县| 延庆县| 连南| 卓资县|