在使用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. MinGW-W64 编译 LLVM 与 Clang

    原文: http://blog.csdn.net/happywjh666/article/details/51415723 编译环境: 系统 --win10 64位 gcc -- version 5. ...

  2. day_03比特币转账的运行原理

    在2008年全球经济危机中,中本聪想如果能构建一个没有中心机构的货币发行体系,货币就不会被无限发行,大家都很公平公正,于是中本聪构建了比特币这样一个体系: 一.非中心化下的比特币发行机制 比特币的发行 ...

  3. qjson中把记录或类型或泛型数组转换为json字符串

    unit Unit4; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System ...

  4. zencart单独屏蔽左右边栏代码

    1.屏蔽左栏:打开模板目录下的tpl_main_page.php文件,找到以下代码 if (!isset($flag_disable_left) || !$flag_disable_left) { 在 ...

  5. P1361 小M的作物 最小割理解

    如果没有组合效益的存在 我们直接每个点两部分的最大值即可 换成网络流模型来看 即把S点看作是A田 把T点看作是B田 每种作物看作一个点 分别连边(S,i,A[i]) (i,T,B[i]) 最后图中所有 ...

  6. Python的安装和配置(windowns 双版本)

    1.去官网上下载python,注意版本. 官网地址:https://www.python.org/downloads/windows 2.下载安装版或者zip包都可以.安装就按向导一步一步完成即可.z ...

  7. unity里framebuffer fetch相关问题

    https://docs.unity3d.com/Manual/SL-PlatformDifferences.html 开了framebuffer fetch 如果你再在里面sample 那张rt ( ...

  8. 题解 [BZOJ4144] Petrol

    题目描述 ​ 有一张 n 个点 m 条边的无向图,其中有 s 个点上有加油站.有 Q 次询问(a,b,c), 问能否开一辆油箱容积为 c 的车从 a 走到 b.(a,b均为加油站) 输入格式 ​ 第一 ...

  9. 传统Spring配置JTA 实现多数据源事务的统一管理

    分布式事务是指事务的参与者.支持事务的服务器.资源管理器以及事务管理器分别位于分布系统的不同节点之上,在两个或多个网络计算机资源上访问并且更新数据,将两个或多个网络计算机的数据进行的多次操作作为一个整 ...

  10. 微软企业库Unity依赖注入

    Unity Application Block 1.0系列(4): 方法调用注入(Method Call Injection ) http://www.cnblogs.com/inrie/archiv ...