在使用Spring Security框架过程中,经常会有这样的需求,即在登录验证时,附带增加额外的数据,如验证码、用户类型等。下面将介绍如何实现。

  注:我的工程是在Spring Boot框架基础上的,使用xml方式配置的话请读者自行研究吧。

  • 实现自定义的WebAuthenticationDetails

  该类提供了获取用户登录时携带的额外信息的功能,默认实现WebAuthenticationDetails提供了remoteAddress与sessionId信息。开发者可以通过Authentication的getDetails()获取WebAuthenticationDetails。我们编写自定义类CustomWebAuthenticationDetails继承自WebAuthenticationDetails,添加我们关心的数据(以下是一个token字段)。

package com.cgs.courses.service;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.web.authentication.WebAuthenticationDetails;

public class CustomWebAuthenticationDetails extends WebAuthenticationDetails {
/**
*
*/
private static final long serialVersionUID = 6975601077710753878L;
private final String token; public CustomWebAuthenticationDetails(HttpServletRequest request) {
super(request);
token = request.getParameter("token");
} public String getToken() {
return token;
} @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append("; Token: ").append(this.getToken());
return sb.toString();
}
}

  注:在登录页面,可将token字段放在form表单中,也可以直接加在url的参数中,进而把额外数据发送给后台。

  • 实现自定义的AuthenticationDetailsSource

  该接口用于在Spring Security登录过程中对用户的登录信息的详细信息进行填充,默认实现是WebAuthenticationDetailsSource,生成上面的默认实现WebAuthenticationDetails。我们编写类实现AuthenticationDetailsSource,用于生成上面自定义的CustomWebAuthenticationDetails。

package com.cgs.courses.service;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component; @Component
public class CustomAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {     @Override
    public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
        return new CustomWebAuthenticationDetails(context);
    }
}
  • 配置使用自定义的AuthenticationDetailsSource

  只要看这一句.formLogin().authenticationDetailsSource(authenticationDetailsSource)

    @Autowired
private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource; protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.cacheControl()
.contentTypeOptions()
.httpStrictTransportSecurity()
.xssProtection()
.and()
.authorizeRequests()
.antMatchers(
"/css/**",
"/js/**")
.permitAll()
.antMatchers("/**")
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/todo.html", true)
.authenticationDetailsSource(authenticationDetailsSource)
.and()
.logout()
.logoutUrl("/logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.and()
.csrf().disable();
}
  • 实现自定义的AuthenticationProvider

  AuthenticationProvider提供登录验证处理逻辑,我们实现该接口编写自己的验证逻辑。

package com.cgs.courses.service;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component; @Component
public class CustomAuthenticationProvider implements AuthenticationProvider { @Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
CustomWebAuthenticationDetails details = (CustomWebAuthenticationDetails) authentication.getDetails(); // 如上面的介绍,这里通过authentication.getDetails()获取详细信息
// System.out.println(details); details.getRemoteAddress(); details.getSessionId(); details.getToken();
// 下面是验证逻辑,验证通过则返回UsernamePasswordAuthenticationToken,
// 否则,可直接抛出错误(AuthenticationException的子类,在登录验证不通过重定向至登录页时可通过session.SPRING_SECURITY_LAST_EXCEPTION.message获取具体错误提示信息)
if (验证通过) {
return UsernamePasswordAuthenticationToken(省略参数);
} else {
throw new AuthenticationException的子类("你要显示的错误信息")
}
} @Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
} }
  • 配置使用自定义的AuthenticationProvider
  @Autowired
    private AuthenticationProvider authenticationProvider;   @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}

Spring Security在登录验证中增加额外数据(如验证码)的更多相关文章

  1. Spring Boot整合Spring Security自定义登录实战

    本文主要介绍在Spring Boot中整合Spring Security,对于Spring Boot配置及使用不做过多介绍,还不了解的同学可以先学习下Spring Boot. 本demo所用Sprin ...

  2. 自定义Spring Security的身份验证失败处理

    1.概述 在本快速教程中,我们将演示如何在Spring Boot应用程序中自定义Spring Security的身份验证失败处理.目标是使用表单登录方法对用户进行身份验证. 2.认证和授权(Authe ...

  3. Spring Security 自定义登录认证(二)

    一.前言 本篇文章将讲述Spring Security自定义登录认证校验用户名.密码,自定义密码加密方式,以及在前后端分离的情况下认证失败或成功处理返回json格式数据 温馨小提示:Spring Se ...

  4. spring security关闭http验证 和 springboot 使用h2数据库

    spring security关闭http验证 最近在跑demo的过程中,访问swagger页面的时候需要验证登录,记得在之前写的代码中是关闭了security验证,无需登录成功访问,直接在appli ...

  5. Spring Security 概念基础 验证流程

    Spring Security 概念基础 验证流程 认证&授权 认证:确定是否为合法用户 授权:分配角色权限(分配角色,分配资源) 认证管理器(Authentication Manager) ...

  6. springboot中使用spring security,登录url就出现403错误

    参考链接:https://segmentfault.com/q/1010000012743613 有两个controller,一个是所有用户可以访问的@RequestMapping("use ...

  7. Spring Security 基础登录实例

    1 新建Java Web项目 导入Jar: 2 修改web.xml <?xml version="1.0" encoding="UTF-8"?> & ...

  8. SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能

    在 Spring Security 中基于表单的认证模式,默认就是密码帐号登录认证,那么对于短信验证码+登录的方式,Spring Security 没有现成的接口可以使用,所以需要自己的封装一个类似的 ...

  9. spring security结合数据库验证用户-XML配置方式

    之前的用户信息我们都是使用的内存用户,测试例子可以,实际中使用肯定不行,需要结合数据库进行验证用户.这就是本节的重点: 项目目录如下:  在之前的项目中的依赖中添加两个依赖: <dependen ...

随机推荐

  1. Oracle笔记(十六) 数据库设计范式

    数据库设计范式是一个很重要的概念,但是这个重要程度只适合于参考.使用数据库设计范式,可以让数据表更好的进行数据的保存,因为再合理的设计,如果数据量一大也肯定会存在性能上的问题.所以在开发之中,唯一可以 ...

  2. 一周死磕fastreport ----ASP.NET (三)

    做了一周,然而说着很快  首先拖一个WebReport 点击design report 设置模板 引入dll using引用 设置好就打印就可以了 未来几天, 然后都在设置样式 ....如何就一周过去 ...

  3. 三种方式构建C#单例模式

    /// <summary> /// 双检锁实现单例 /// </summary> public sealed class SingletonDoubleCheck { //s_ ...

  4. selenium八种定位元素方法

    1.driver.find_element_by_id('su') 定位到元素的id一般id是唯一的,可以精确定位到元素 2.driver.find_element_by_name() 通过元素的na ...

  5. bash: hexo: command not found

    问题 很久没写博客了,今天用hexo新建文章时git报错: bash: hexo: command not found 解决办法 百度之后,将D:\WorkingSoftware\GithubBlog ...

  6. Django的 select_related 和 prefetch_related 函数对 QuerySet 查询的优化

    引言 在数据库存在外键的其情况下,使用select_related()和prefetch_related()很大程度上减少对数据库的请求次数以提高性能 1.实例准备 模型: from django.d ...

  7. 数据结构系列文章之队列 FIFO

    转载自https://mp.weixin.qq.com/s/ILgdI7JUBsiATFICyyDQ9w Osprey  鱼鹰谈单片机 3月2日 预计阅读时间: 6 分钟 这里的 FIFO 是先入先出 ...

  8. 音频转换 wav to wav、mp3或者其它

    1.首先介绍一种NAudio 的方式 需要导入 NAudio.dll 下面请看核心代码 using (WaveFileReader reader = new WaveFileReader(in_pat ...

  9. rsync 同步操作

    同步:增量拷贝,只传输变化过的数据 rsync   [ 选项]  源目录/目标目录 -a :归档模式  相当于 -rlptgoD -v:显示详细操作信息 -z:传输过程中启用压缩/解压 --delet ...

  10. Python2.x与3​​.x版本区别Ⅱ

    除法运算 Python中的除法较其它语言显得非常高端,有套很复杂的规则.Python中的除法有两个运算符,/和// 首先来说/除法: 在python 2.x中/除法就跟我们熟https://www.x ...