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

Spring?Security配置多個數(shù)據(jù)源并添加登錄驗(yàn)證碼的實(shí)例代碼

 更新時間:2022年08月04日 12:06:47   作者:liwenruo  
這篇文章主要介紹了Spring?Security配置多個數(shù)據(jù)源并添加登錄驗(yàn)證碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1.配置多個數(shù)據(jù)源

多個數(shù)據(jù)源是指在同一個系統(tǒng)中,用戶數(shù)據(jù)來自不同的表,在認(rèn)證時,如果第一張表沒有查找到用戶,那就去第二張表中査詢,依次類推。

看了前面的分析,要實(shí)現(xiàn)這個需求就很容易了,認(rèn)證要經(jīng)過AuthenticationProvider,每一 個 AuthenticationProvider 中都配置了一個 UserDetailsService,而不同的 UserDetailsService 則可以代表不同的數(shù)據(jù)源,所以我們只需要手動配置多個AuthenticationProvider,并為不同的 AuthenticationProvider 提供不同的 UserDetailsService 即可。

為了方便起見,這里通過 InMemoryUserDetailsManager 來提供 UserDetailsService 實(shí)例, 在實(shí)際開發(fā)中,只需要將UserDetailsService換成自定義的即可,具體配置如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    @Primary
    UserDetailsService us1(){
        return new InMemoryUserDetailsManager(User.builder().username("testuser1").password("{noop}123")
                .roles("admin").build());
    }
    @Bean
    UserDetailsService us2(){
        return new InMemoryUserDetailsManager(User.builder().username("testuser2").password("{noop}123")
                .roles("user").build());
    }
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        DaoAuthenticationProvider dao1 = new DaoAuthenticationProvider();
        dao1.setUserDetailsService(us1());
        DaoAuthenticationProvider dao2 = new DaoAuthenticationProvider();
        dao2.setUserDetailsService(us2());
        ProviderManager manager = new ProviderManager(dao1, dao2);
        return manager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //省略
    }
}

首先定義了兩個UserDetailsService實(shí)例,不同實(shí)例中存儲了不同的用戶;然后重寫 authenticationManagerBean 方法,在該方法中,定義了兩個 DaoAuthenticationProvider 實(shí)例并分別設(shè)置了不同的UserDetailsService ;最后構(gòu)建ProviderManager實(shí)例并傳入兩個 DaoAuthenticationProvider,當(dāng)系統(tǒng)進(jìn)行身份認(rèn)證操作時,就會遍歷ProviderManager中不同的 DaoAuthenticationProvider,進(jìn)而調(diào)用到不同的數(shù)據(jù)源。

2. 添加登錄驗(yàn)證碼

登錄驗(yàn)證碼也是項(xiàng)目中一個常見的需求,但是Spring Security對此并未提供自動化配置方案,需要開發(fā)者自行定義,一般來說,有兩種實(shí)現(xiàn)登錄驗(yàn)證碼的思路:

  • 自定義過濾器。
  • 自定義認(rèn)證邏輯。

通過自定義過濾器來實(shí)現(xiàn)登錄驗(yàn)證碼,這種方案我們會在后面的過濾器中介紹, 這里先來看如何通過自定義認(rèn)證邏輯實(shí)現(xiàn)添加登錄驗(yàn)證碼功能。

生成驗(yàn)證碼,可以自定義一個生成工具類,也可以使用一些現(xiàn)成的開源庫來實(shí)現(xiàn),這里 采用開源庫kaptcha,首先引入kaptcha依賴,代碼如下:

<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

然后對kaptcha進(jìn)行配置:

?package com.intehel.demo.config;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class KaptchaConfig {
    @Bean
    Producer kaptcha(){
        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width", "150");
        properties.setProperty("kaptcha.image.height", "50");
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

配置一個Producer實(shí)例,主要配置一下生成的圖片驗(yàn)證碼的寬度、長度、生成字符、驗(yàn)證碼的長度等信息,配置完成后,我們就可以在Controller中定義一個驗(yàn)證碼接口了。

?package com.intehel.demo.controller;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class LoginController {
    @Autowired
    Producer producer;
    @RequestMapping("/vc.jpg")
    public void getVerifyCode(HttpServletResponse resp, HttpSession session){
        resp.setContentType("image/jpeg");
        String text = producer.createText();
        session.setAttribute("kaptcha",text);
        BufferedImage image = producer.createImage(text);
        try(ServletOutputStream out = resp.getOutputStream()) {
            ImageIO.write(image,"jpg",out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在這個驗(yàn)證碼接口中,我們主要做了兩件事:

  • 生成驗(yàn)證碼文本,并將文本存入HttpSession中。
  • 根據(jù)驗(yàn)證碼文本生成驗(yàn)證碼圖片,并通過IO流寫出到前端。

接下來修改登錄表單,加入驗(yàn)證碼,代碼如下:

?<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
    <link  rel="stylesheet" id="bootstrap-css">
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<style>
    #login .container #login-row #login-column #login-box {
        border: 1px solid #9c9c9c;
        background-color: #EAEAEA;
    }
</style>
<body>
<div id="login">
    <div class="container">
        <div id="login-row" class="row justify-content-center align-items-center">
            <div id="login-column" class="col-md-6">
                <div id="login-box" class="col-md-12">
                    <form id="login-form" class="form" action="/doLogin" method="post">
                        <h3 class="text-center text-info">登錄</h3>
                        <!--/*@thymesVar id="SPRING_SECURITY_LAST_EXCEPTION" type="com"*/-->
                        <div th:text="${SPRING_SECURITY_LAST_EXCEPTION}"></div>
                        <div class="form-group">
                            <label for="username" class="text-info">用戶名:</label><br>
                            <input type="text" name="uname" id="username" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="password" class="text-info">密碼:</label><br>
                            <input type="text" name="passwd" id="password" class="form-control">
                        </div>
                        <div class="form-group">
                            <label for="kaptcha" class="text-info">驗(yàn)證碼:</label><br>
                            <input type="text" name="kaptcha" id="kaptcha" class="form-control">
                            <img src="/vc.jpg" alt="">
                        </div>
                        <div class="form-group">
                            <input type="submit" name="submit" class="btn btn-info btn-md" value="登錄">
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>??

登錄表單中增加一個驗(yàn)證碼輸入框,驗(yàn)證碼的圖片地址就是我們在Controller中定義的驗(yàn)證碼接口地址。

接下來就是驗(yàn)證碼的校驗(yàn)了。經(jīng)過前面的介紹,讀者已經(jīng)了解到,身份認(rèn)證實(shí)際上就是在AuthenticationProvider.authenticate方法中完成的。所以,驗(yàn)證碼的校驗(yàn),我們可以在該方法執(zhí)行之前進(jìn)行,需要配置如下類:

?package com.intehel.demo.provider;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

public class KaptchaAuthenticationProvider extends DaoAuthenticationProvider{
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String kaptcha = req.getParameter("kaptcha");
        String serssionKaptcha = (String) req.getSession().getAttribute("kaptcha");
        if (kaptcha != null && serssionKaptcha != null && kaptcha.equalsIgnoreCase(serssionKaptcha)){
            return super.authenticate(authentication);
        }
        throw new AuthenticationServiceException("驗(yàn)證碼輸入錯誤");
    }
}

這里重寫authenticate方法,在authenticate方法中,從RequestContextHolder中獲取當(dāng)前請求,進(jìn)而獲取到驗(yàn)證碼參數(shù)和存儲在HttpSession中的驗(yàn)證碼文本進(jìn)行比較,比較通過則繼續(xù)執(zhí)行父類的authenticate方法,比較不通過,就拋出異常。

你可能會想到通過重寫 DaoAuthenticationProvider類的 additionalAuthenticationChecks 方法來完成驗(yàn)證碼的校驗(yàn),這個從技術(shù)上來說是沒有問題的,但是這會讓驗(yàn)證碼失去存在的意義,因?yàn)楫?dāng)additionalAuthenticationChecks方法被調(diào)用時,數(shù)據(jù)庫查詢已經(jīng)做了,僅僅剩下密碼沒有校驗(yàn),此時,通過驗(yàn)證碼來攔截惡意登錄的功能就已經(jīng)失效了。

最后,在 SecurityConfig 中配置 AuthenticationManager,代碼如下:

?package com.intehel.demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.intehel.demo.Service.MyUserDetailsService;
import com.intehel.demo.handler.MyAuthenticationFailureHandler;
import com.intehel.demo.provider.KaptchaAuthenticationProvider;
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.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserDetailsService myUserDetailsService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/vc.jpg").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/mylogin.html")
                .loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/index.html")
                .failureHandler(new MyAuthenticationFailureHandler())
                .usernameParameter("uname")
                .passwordParameter("passwd")
                .permitAll()
                .and()
                .logout()
                .logoutRequestMatcher(new OrRequestMatcher(new AntPathRequestMatcher("/logout1","GET"),
                        new AntPathRequestMatcher("/logout2","POST")))
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .defaultLogoutSuccessHandlerFor((req,resp,auth)->{
                    resp.setContentType("application/json;charset=UTF-8");
                    Map<String,Object> result = new HashMap<String,Object>();
                    result.put("status",200);
                    result.put("msg","使用logout1注銷成功!");
                    ObjectMapper om = new ObjectMapper();
                    String s = om.writeValueAsString(result);
                    resp.getWriter().write(s);
                },new AntPathRequestMatcher("/logout1","GET"))
                .defaultLogoutSuccessHandlerFor((req,resp,auth)->{
                    resp.setContentType("application/json;charset=UTF-8");
                    Map<String,Object> result = new HashMap<String,Object>();
                    result.put("status",200);
                    result.put("msg","使用logout2注銷成功!");
                    ObjectMapper om = new ObjectMapper();
                    String s = om.writeValueAsString(result);
                    resp.getWriter().write(s);
                },new AntPathRequestMatcher("/logout1","GET"))
                .and()
                .csrf().disable();
    }
    @Bean
    AuthenticationProvider kaptchaAuthenticationProvider(){
        KaptchaAuthenticationProvider provider = new KaptchaAuthenticationProvider();
        provider.setUserDetailsService(myUserDetailsService);
        return provider;
    }

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        ProviderManager manager = new ProviderManager(kaptchaAuthenticationProvider());
        return manager;
    }
}

 

這里配置分三步:首先配置UserDetailsService提供數(shù)據(jù)源;然后提供一個 AuthenticationProvider 實(shí)例并配置 UserDetailsService;最后重寫 authenticationManagerBean 方 法,提供一個自己的PioviderManager并使用自定義的AuthenticationProvider實(shí)例。

另外需要注意,在configure(HttpSecurity)方法中給驗(yàn)證碼接口配置放行,permitAll表示這個接口不需要登錄就可以訪問。

配置完成后,啟動項(xiàng)目,瀏覽器中輸入任意地址都會跳轉(zhuǎn)到登錄頁面,如圖3-5所示。

 

圖 3-5

此時,輸入用戶名、密碼以及驗(yàn)證碼就可以成功登錄。如果驗(yàn)證碼輸入錯誤,則登錄頁面會自動展示錯誤信息,如下:

 

到此這篇關(guān)于Spring Security配置多個數(shù)據(jù)源并添加登錄驗(yàn)證碼的文章就介紹到這了,更多相關(guān)Spring Security登錄驗(yàn)證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring Security實(shí)現(xiàn)兩周內(nèi)自動登錄

    Spring Security實(shí)現(xiàn)兩周內(nèi)自動登錄"記住我"功能

    登錄過程中經(jīng)常使用的“記住我”功能,也就是我們經(jīng)常會在各種網(wǎng)站登陸時見到的"兩周內(nèi)免登錄",“三天內(nèi)免登錄”的功能。今天小編給大家分享基于Spring Security實(shí)現(xiàn)兩周內(nèi)自動登錄"記住我"功能,感興趣的朋友一起看看吧
    2019-11-11
  • SpringBoot分頁的實(shí)現(xiàn)與long型id精度丟失問題的解決方案介紹

    SpringBoot分頁的實(shí)現(xiàn)與long型id精度丟失問題的解決方案介紹

    在以后的開發(fā)中,當(dāng)全局唯一id的生成策略生成很長的Long型數(shù)值id之后會超過JS對Long型數(shù)據(jù)處理的能力范圍,可能發(fā)生精度丟失而造成后端方法失效,我們要學(xué)會解決。分頁功能雖然簡單但是非常重要,對于剛接觸項(xiàng)目的人一定要重點(diǎn)注意
    2022-10-10
  • java爬蟲之使用HttpClient模擬瀏覽器發(fā)送請求方法詳解

    java爬蟲之使用HttpClient模擬瀏覽器發(fā)送請求方法詳解

    這篇文章主要介紹了java爬蟲之使用HttpClient模擬瀏覽器發(fā)送請求方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • java中獲取xml文件的某個配置節(jié)點(diǎn)內(nèi)容方式

    java中獲取xml文件的某個配置節(jié)點(diǎn)內(nèi)容方式

    這篇文章主要介紹了java中獲取xml文件的某個配置節(jié)點(diǎn)內(nèi)容方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • 解決spring懶加載以及@PostConstruct結(jié)合的坑

    解決spring懶加載以及@PostConstruct結(jié)合的坑

    這篇文章主要介紹了解決spring懶加載以及@PostConstruct結(jié)合的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java實(shí)現(xiàn)輸出回環(huán)數(shù)(螺旋矩陣)的方法示例

    Java實(shí)現(xiàn)輸出回環(huán)數(shù)(螺旋矩陣)的方法示例

    這篇文章主要介紹了Java實(shí)現(xiàn)輸出回環(huán)數(shù)(螺旋矩陣)的方法,涉及java針對數(shù)組的遍歷、判斷、輸出等相關(guān)操作技巧,需要的朋友可以參考下
    2017-12-12
  • Java 對稱加密幾種算法分別實(shí)現(xiàn)

    Java 對稱加密幾種算法分別實(shí)現(xiàn)

    這篇文章主要介紹了Java 對稱加密使用DES / 3DES / AES 這三種算法分別實(shí)現(xiàn)的相關(guān)資料,這里提供了實(shí)例代碼,需要的朋友可以參考下
    2017-01-01
  • JavaSE詳細(xì)講解異常語法

    JavaSE詳細(xì)講解異常語法

    異常就是不正常,比如當(dāng)我們身體出現(xiàn)了異常我們會根據(jù)身體情況選擇喝開水、吃藥、看病、等 異常處理方法。 java異常處理機(jī)制是我們java語言使用異常處理機(jī)制為程序提供了錯誤處理的能力,程序出現(xiàn)的錯誤,程序可以安全的退出,以保證程序正常的運(yùn)行等
    2022-05-05
  • SpringBoot在項(xiàng)目中訪問靜態(tài)資源步驟分析

    SpringBoot在項(xiàng)目中訪問靜態(tài)資源步驟分析

    今天在玩SpringBoot的demo的時候,放了張圖片在resources目錄下,啟動區(qū)訪問的時候,突然好奇是識別哪些文件夾來展示靜態(tài)資源的, 為什么有時候放的文件夾不能顯示,有的卻可以
    2023-01-01
  • 教你如何用Java根據(jù)日期生成流水號

    教你如何用Java根據(jù)日期生成流水號

    這篇文章主要介紹了教你如何用Java根據(jù)日期生成流水號,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-04-04

最新評論

叙永县| 婺源县| 韩城市| 商南县| 长沙市| 云阳县| 高台县| 大同县| 明溪县| 临湘市| 石阡县| 陕西省| 九龙城区| 应用必备| 乡宁县| 贡觉县| 天全县| 资溪县| 绥棱县| 东城区| 武城县| 遂宁市| 阜城县| 安丘市| 敖汉旗| 宝应县| 长寿区| 曲沃县| 桦川县| 方城县| 郸城县| 光泽县| 黑水县| 开平市| 酒泉市| 九寨沟县| 中宁县| 陵水| 惠东县| 霍山县| 庐江县|