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

spring boot security自定義認(rèn)證的代碼示例

 更新時間:2023年07月05日 09:30:26   作者:不識君的荒漠  
這篇文章主要介紹了spring boot security自定義認(rèn)證,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

前言

前置閱讀

spring boot security快速使用示例

SpringBoot+Vue前后端分離,使用SpringSecurity完美處理權(quán)限問題的解決方法

說明

實際場景,我們一般是把用戶信息保存在db中(也可能是調(diào)用三方接口),需要自定義用戶信息加載或認(rèn)證部分的邏輯,下面提供一個示例。

代碼示例

定義用戶bean

@AllArgsConstructor
@Data
public class User {
    private String username;
    private String password;
}

定義Mapper

示例,代碼寫死了,并不是實際從數(shù)據(jù)庫或某個存儲查詢用戶信息:

@Component
public class UserMapper {
   public User select(String username) {
        return new User(username, "pass");
    }
}

定義加載用戶數(shù)據(jù)的類

UserDetailsService 是spring security內(nèi)置的加載用戶信息的接口,我們只需要實現(xiàn)這個接口:

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    public static final UserDetails INVALID_USER =
            new org.springframework.security.core.userdetails.User("invalid_user", "invalid_password", Collections.emptyList());
    private final UserMapper userMapper;
    public UserDetailsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根據(jù)用戶名從數(shù)據(jù)庫查詢用戶信息
        User user = userMapper.select(username);
        if (user == null) {
            /**
             * 如果沒查詢到這個用戶,考慮兩種選擇:
             * 1. 返回一個標(biāo)記無效用戶的常量對象
             * 2. 返回一個不可能認(rèn)證通過的用戶
             */
            return INVALID_USER;
//            return new User(username, System.currentTimeMillis() + UUID.randomUUID().toString(), Collections.emptyList());
        }
        /**
         * 這里返回的用戶密碼是否為庫里保存的密碼,是明文/密文,取決于認(rèn)證時密碼比對部分的實現(xiàn),每個人的場景不一樣,
         * 因為使用的是不加密的PasswordEncoder,所以可以返回明文
         */
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), Collections.emptyList());
    }
}

自定義認(rèn)證的bean配置

@Configuration
public class WebConfiguration {
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 示例,不對密碼進(jìn)行加密處理
        return NoOpPasswordEncoder.getInstance();
    }
    @Bean
    public AuthenticationManager authenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        // 設(shè)置加載用戶信息的類
        provider.setUserDetailsService(userDetailsService);
        // 比較用戶密碼的時候,密碼加密方式
        provider.setPasswordEncoder(passwordEncoder);
        return new ProviderManager(Arrays.asList(provider));
    }
}

注意,因為這個是示例,AuthenticationProvider使用的是spring security的DaoAuthenticationProvider ,在實際場景中,如果不滿足可以自定義實現(xiàn)或者繼承DaoAuthenticationProvider ,重寫其中的:additionalAuthenticationChecks方法,主要就是認(rèn)證檢查的,默認(rèn)實現(xiàn)如下:

@Override
	@SuppressWarnings("deprecation")
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
		if (authentication.getCredentials() == null) {
			this.logger.debug("Failed to authenticate since no credentials provided");
			throw new BadCredentialsException(this.messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
		String presentedPassword = authentication.getCredentials().toString();
		// 就是比對下請求傳過來的密碼和根據(jù)該用戶查詢的密碼是否一致,passwordEncoder是根據(jù)不同的加密算法進(jìn)行加密,示例我們用的是NoOpPasswordEncoder,也就是原始明文比對
		if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
			this.logger.debug("Failed to authenticate since password does not match stored value");
			throw new BadCredentialsException(this.messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
	}

定義登錄接口

@RequestMapping("/login")
@RestController
public class LoginController {
    private final AuthenticationManager authenticationManager;
    public LoginController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
    @PostMapping()
    public Object login(@RequestBody User user) {
        try {
            // 使用定義的AuthenticationManager進(jìn)行認(rèn)證處理
            Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
            // 認(rèn)證通過,設(shè)置到當(dāng)前上下文,如果當(dāng)前認(rèn)證過程后續(xù)還有處理的邏輯需要的話。這個示例是沒有必要了
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            return "login success";
        }catch (Exception e) {
            return "login failed";
        }
    }
    /**
     * 獲取驗證碼,需要的話,可以提供一個驗證碼獲取的接口,在上面的login里把驗證碼傳進(jìn)來進(jìn)行比對
     */
    @GetMapping("/captcha")
    public Object captcha() {
        return "1234";
    }
}

自定義HttpSecurity

@Component
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 在這里自定義配置
        http.authorizeRequests()
                // 登錄相關(guān)接口都允許訪問
                .antMatchers("/login/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling()
                // 認(rèn)證失敗返回401狀態(tài)碼,前端頁面可以根據(jù)401狀態(tài)碼跳轉(zhuǎn)到登錄頁面
                .authenticationEntryPoint((request, response, authException) ->
                        response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()))
                .and().cors()
                // csrf是否決定禁用,請自行考量
                .and().csrf().disable()
                // 采用http 的基本認(rèn)證.
                .httpBasic();
    }
}

測試

示例中,用戶密碼寫死是:pass,用一個錯誤的密碼試一下,響應(yīng)登錄失?。?/p>

在這里插入圖片描述

使用正確的密碼,響應(yīng)登錄成功:

在這里插入圖片描述

到此這篇關(guān)于spring boot security自定義認(rèn)證的文章就介紹到這了,更多相關(guān)spring boot security自定義認(rèn)證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • windows下 jdk1.7安裝教程圖解

    windows下 jdk1.7安裝教程圖解

    java編程的初學(xué)者在開始編碼前都會遇到一個難題,那就是jdk1.7環(huán)境變量配置怎么操作,怎么安裝,針對這個難題,小編特地為大家整理相關(guān)教程,不了解的朋友可以前往查看使用
    2018-05-05
  • idea 多模塊項目依賴父工程class找不到問題的方法

    idea 多模塊項目依賴父工程class找不到問題的方法

    這篇文章主要介紹了idea 多模塊項目依賴父工程class找不到問題的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01
  • java迭代子模式詳解

    java迭代子模式詳解

    這篇文章主要為大家詳細(xì)介紹了java迭代子模式的相關(guān)資料,需要的朋友可以參考下
    2016-02-02
  • Java?獲取Zookeeper節(jié)點下所有數(shù)據(jù)詳細(xì)步驟

    Java?獲取Zookeeper節(jié)點下所有數(shù)據(jù)詳細(xì)步驟

    本文介紹了如何使用Java獲取ZooKeeper節(jié)點下所有數(shù)據(jù),實際應(yīng)用示例中,我們演示了如何從ZooKeeper節(jié)點下獲取配置信息并輸出到控制臺,ZooKeeper是一個開源的分布式協(xié)調(diào)服務(wù),適用于分布式系統(tǒng)中的數(shù)據(jù)同步、配置管理、命名服務(wù)等功能,感興趣的朋友一起看看吧
    2024-11-11
  • idea啟動Tomcat時控制臺亂碼的解決方法(親測有效)

    idea啟動Tomcat時控制臺亂碼的解決方法(親測有效)

    最近在idea中啟動tomcat出現(xiàn)控制臺亂碼問題,嘗試了很多方法,最后終于解決了,所以下面這篇文章主要給大家介紹了關(guān)于idea啟動Tomcat時控制臺亂碼的解決方法,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • springboot vue完成編輯頁面發(fā)送接口請求功能

    springboot vue完成編輯頁面發(fā)送接口請求功能

    這篇文章主要為大家介紹了springboot+vue完成編輯頁發(fā)送接口請求功能,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • 一文帶你了解Java中的SPI機制

    一文帶你了解Java中的SPI機制

    SPI 全稱是 Service Provider Interface,是一種 JDK 內(nèi)置的動態(tài)加載實現(xiàn)擴展點的機制,本文主要為大家介紹了SPI機制的原理與使用,需要的可以參考一下
    2023-04-04
  • 詳解Java的引用類型及使用場景

    詳解Java的引用類型及使用場景

    這篇文章主要介紹了詳解Java的引用類型及使用場景,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下
    2021-03-03
  • Java基礎(chǔ)高級綜合練習(xí)題撲克牌的創(chuàng)建

    Java基礎(chǔ)高級綜合練習(xí)題撲克牌的創(chuàng)建

    今天小編就為大家分享一篇關(guān)于Java基礎(chǔ)高級綜合練習(xí)題撲克牌的創(chuàng)建,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • Java設(shè)計模式之策略模式詳解

    Java設(shè)計模式之策略模式詳解

    這篇文章主要為大家詳細(xì)介紹了Java設(shè)計模式之策略模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-10-10

最新評論

沐川县| 武川县| 长治市| 石首市| 遂川县| 准格尔旗| 萍乡市| 蒙城县| 根河市| 苏尼特右旗| 象山县| 资兴市| 宾川县| 英超| 金乡县| 芒康县| 新乡市| 岳阳县| 广河县| 北辰区| 东丽区| 防城港市| 安多县| 旌德县| 尖扎县| 周至县| 西宁市| 罗定市| 靖西县| 武宣县| 和林格尔县| 白朗县| 石阡县| 孝昌县| 东明县| 张家港市| 靖江市| 太白县| 启东市| 阳谷县| 辽中县|