国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

香港云服务器
服務(wù)器之家 - 編程語言 - Java教程 - Spring Security添加驗(yàn)證碼的兩種方式小結(jié)

Spring Security添加驗(yàn)證碼的兩種方式小結(jié)

2022-02-12 15:27周杰倫本人 Java教程

使用spring security的時(shí)候,框架會(huì)幫我們做賬戶密碼的驗(yàn)證,但是如我們需要添加一個(gè)驗(yàn)證碼,就需要對(duì)配置文件進(jìn)行修改,這篇文章主要給大家介紹了關(guān)于Spring Security添加驗(yàn)證碼的兩種方式,需要的朋友可以參考下

一、自定義認(rèn)證邏輯

生成驗(yàn)證碼工具

?
1
2
3
4
5
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

添加Kaptcha配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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;
    }
}

生成驗(yàn)證碼文本,放入HttpSession中

根據(jù)驗(yàn)證碼文本生成圖片 通過IO流寫出到前端。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@RestController
public class LoginController {
    @Autowired
    Producer producer;
    @GetMapping("/vc.jpg")
    public void getVerifyCode(HttpServletResponse resp, HttpSession session) throws IOException {
        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);
        }
    }
    @RequestMapping("/index")
    public String index() {
        return "login success";
    }
    @RequestMapping("/hello")
    public String hello() {
        return "hello spring security";
    }
}

form表單

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="external nofollow"  rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    <script src="//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>
                        <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>

驗(yàn)證碼圖片地址為我們?cè)贑ontroller中定義的驗(yàn)證碼接口地址。

身份認(rèn)證是AuthenticationProvider的authenticate方法完成,因此驗(yàn)證碼可以在此之前完成:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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 sessionKaptcha = (String) req.getSession().getAttribute("kaptcha");
        if (kaptcha != null && sessionKaptcha != null && kaptcha.equalsIgnoreCase(sessionKaptcha)) {
            return super.authenticate(authentication);
        }
        throw new AuthenticationServiceException("驗(yàn)證碼輸入錯(cuò)誤");
    }
}

配置AuthenticationManager:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Bean
    AuthenticationProvider kaptchaAuthenticationProvider() {
        InMemoryUserDetailsManager users = new InMemoryUserDetailsManager(User.builder()
                .username("xiepanapn").password("{noop}123").roles("admin").build());
        KaptchaAuthenticationProvider provider = new KaptchaAuthenticationProvider();
        provider.setUserDetailsService(users);
        return provider;
    }
 
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        ProviderManager manager = new ProviderManager(kaptchaAuthenticationProvider());
        return manager;
    }
 
    @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")
                .failureForwardUrl("/mylogin.html")
                .usernameParameter("uname")
                .passwordParameter("passwd")
                .permitAll()
                .and()
                .csrf().disable();
    }
}
  1. 配置UserDetailsService提供的數(shù)據(jù)源
  2. 提供AuthenticationProvider實(shí)例并配置UserDetailsService
  3. 重寫authenticationManagerBean方法提供一個(gè)自己的ProviderManager并自定義AuthenticationManager實(shí)例。

二、自定義過濾器

LoginFilter繼承UsernamePasswordAuthenticationFilter 重寫attemptAuthentication方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
 
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        String kaptcha = request.getParameter("kaptcha");
        String sessionKaptcha = (String) request.getSession().getAttribute("kaptcha");
        if (!StringUtils.isEmpty(kaptcha) && !StringUtils.isEmpty(sessionKaptcha) && kaptcha.equalsIgnoreCase(sessionKaptcha)) {
            return super.attemptAuthentication(request, response);
        }
        throw new AuthenticationServiceException("驗(yàn)證碼輸入錯(cuò)誤");
    }
}

在SecurityConfig中配置LoginFilter

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication()
                .withUser("javaboy")
                .password("{noop}123")
                .roles("admin");
    }
 
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean()
            throws Exception {
        return super.authenticationManagerBean();
    }
 
    @Bean
    LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setFilterProcessesUrl("/doLogin");
        loginFilter.setAuthenticationManager(authenticationManagerBean());
        loginFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/hello"));
        loginFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/mylogin.html"));
        return loginFilter;
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/vc.jpg").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/mylogin.html")
                .permitAll()
                .and()
                .csrf().disable();
        http.addFilterAt(loginFilter(),
                UsernamePasswordAuthenticationFilter.class);
    }
}

顯然第二種比較簡(jiǎn)單

總結(jié)

到此這篇關(guān)于Spring Security添加驗(yàn)證碼的兩種方式的文章就介紹到這了,更多相關(guān)Spring Security添加驗(yàn)證碼內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

原文鏈接:https://juejin.cn/post/7016269020861038623

延伸 · 閱讀

精彩推薦
755
主站蜘蛛池模板: 91久久国产精品 | 日韩欧美二区 | 久久精品亚洲精品 | 亚洲精品偷拍自拍 | 国产一区二区三区精品久久久 | 欧美一级在线观看 | 国产成人免费在线 | 免费观看毛片 | 性色网 | 性欧美久久久 | 国产免费自拍 | 欧美日韩中文字幕 | aaa在线免费观看 | 亚洲综合自拍 | 日本一区二区在线视频 | 日韩中文视频 | 成人综合视频网 | 超碰人人爱人人 | 特级西西人体4444xxxx | 91麻豆蜜桃一区二区三区 | 久久久久久久一区 | 亚洲激情中文字幕 | 国产综合久久 | 久久国产精品免费一区二区三区 | 成人在线免费看视频 | 日日视频 | 在线看的av| 视频在线一区二区 | 亚洲国产精品久久 | 国产精品九九九 | 亚洲国产精品99久久久久久久久 | 久久精品一区二区国产 | 伦理自拍 | 午夜午夜精品一区二区三区文 | 日韩中文一区二区三区 | 久久综合久色欧美综合狠狠 | 91精品国产综合久久小仙女陆萱萱 | 亚洲免费影院 | 欧美一级看片a免费观看 | 中文字幕乱码亚洲精品一区 | 久久久国产一区二区 |