仅对此用户禁用 java_Spring Security实现禁止用户重复登陆的配置原理

这篇文章主要介绍了Spring Security实现禁止用户重复登陆的配置原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

系统使用了Spring Security做权限管理,现在对于系统的用户,需要改动配置,实现无法多地登陆。

一、SpringMVC项目,配置如下:

首先在修改Security相关的XML,我这里是spring-security.xml,修改UsernamePasswordAuthenticationFilter相关Bean的构造配置

加入

新增sas的Bean及其相关配置

class="org.springframework.security.core.session.SessionRegistryImpl" />

加入ConcurrentSessionFilter相关Bean配置

class="org.springframework.security.web.session.ConcurrentSessionFilter">

class="org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy">

二、SpringBoot项目

三、Bean配置说明

SessionAuthenticationStrategy:该接口中存在onAuthentication方法用于对新登录用户进行session相关的校验。

查看UsernamePasswordAuthenticationFilter及其父类代码,可以发现在doFilter中存在sessionStrategy.onAuthentication(authResult, request, response);方法

但UsernamePasswordAuthenticationFilter中的sessionStrategy对象默认为NullAuthenticatedSessionStrategy,即不对session进行相关验证。

如本文配置,建立id为sas的CompositeSessionAuthenticationStrategy的Bean对象。

CompositeSessionAuthenticationStrategy可以理解为一个托管类,托管所有实现SessionAuthenticationStrategy接口的对象,用来批量托管执行onAuthentication函数

这里CompositeSessionAuthenticationStrategy中注入了三个对象,关注ConcurrentSessionControlAuthenticationStrategy,它实现了对于session并发的控制

UsernamePasswordAuthenticationFilter的Bean中注入新配置的sas,用于替换原本的NullAuthenticatedSessionStrategy

ConcurrentSessionFilter的Bean用来验证session是否失效,并通过SimpleRedirectSessionInformationExpiredStrategy将失败访问进行跳转。

四、代码流程说明(这里模拟用户现在A处登录,随后用户在B处登录,之后A处再进行操作时会返回失败,提示重新登录)

1、用户在A处登录,UsernamePasswordAuthenticationFilter调用sessionStrategy.onAuthentication进行session验证

2、ConcurrentSessionControlAuthenticationStrategy中的onAuthentication开始进行session验证,服务器中保存了登录后的session

/**

* In addition to the steps from the superclass, the sessionRegistry will be updated

* with the new session information.

*/

public void onAuthentication(Authentication authentication,

HttpServletRequest request, HttpServletResponse response) {

//根据所登录的用户信息,查询相对应的现存session列表

final List sessions = sessionRegistry.getAllSessions(

authentication.getPrincipal(), false);

int sessionCount = sessions.size();

//获取session并发数量,对于XML中的maximumSessions

int allowedSessions = getMaximumSessionsForThisUser(authentication);

//判断现有session列表数量和并发控制数间的关系

//如果是首次登录,根据xml配置,这里应该是0<1,程序将会继续向下执行,

//最终执行到SessionRegistryImpl的registerNewSession进行新session的保存

if (sessionCount < allowedSessions) {

// They haven't got too many login sessions running at present

return;

}

if (allowedSessions == -1) {

// We permit unlimited logins

return;

}

if (sessionCount == allowedSessions) {

//获取本次http请求的session

HttpSession session = request.getSession(false);

if (session != null) {

// Only permit it though if this request is associated with one of the

// already registered sessions

for (SessionInformation si : sessions) {

//循环已保存的session列表,判断本次http请求session是否已经保存

if (si.getSessionId().equals(session.getId())) {

//本次http请求是有效请求,返回执行下一个filter

return;

}

}

}

// If the session is null, a new one will be created by the parent class,

// exceeding the allowed number

}

//本次http请求为新请求,进入具体判断

allowableSessionsExceeded(sessions, allowedSessions, sessionRegistry);

}

/**

* Allows subclasses to customise behaviour when too many sessions are detected.

*

* @param sessions either null or all unexpired sessions associated with

* the principal

* @param allowableSessions the number of concurrent sessions the user is allowed to

* have

* @param registry an instance of the SessionRegistry for subclass use

*

*/

protected void allowableSessionsExceeded(List sessions,

int allowableSessions, SessionRegistry registry)

throws SessionAuthenticationException {

//根据exceptionIfMaximumExceeded判断是否要将新http请求拒绝

//exceptionIfMaximumExceeded也可以在XML中配置

if (exceptionIfMaximumExceeded || (sessions == null)) {

throw new SessionAuthenticationException(messages.getMessage(

"ConcurrentSessionControlAuthenticationStrategy.exceededAllowed",

new Object[] { Integer.valueOf(allowableSessions) },

"Maximum sessions of {0} for this principal exceeded"));

}

// Determine least recently used session, and mark it for invalidation

SessionInformation leastRecentlyUsed = null;

//若不拒绝新请求,遍历现存seesion列表

for (SessionInformation session : sessions) {

//获取上一次/已存的session信息

if ((leastRecentlyUsed == null)

|| session.getLastRequest()

.before(leastRecentlyUsed.getLastRequest())) {

leastRecentlyUsed = session;

}

}

//将上次session信息写为无效(欺骗)

leastRecentlyUsed.expireNow();

}

3、用户在B处登录,再次通过ConcurrentSessionControlAuthenticationStrategy的检查,将A处登录的session置于无效状态,并在session列表中添加本次session

4、用户在A处尝试进行其他操作,ConcurrentSessionFilter进行Session相关的验证,发现A处用户已经失效,提示重新登录

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;

HttpServletResponse response = (HttpServletResponse) res;

//获取本次http请求的session

HttpSession session = request.getSession(false);

if (session != null) {

//从本地session关系表中取出本次http访问的具体session信息

SessionInformation info = sessionRegistry.getSessionInformation(session

.getId());

//如果存在信息,则继续执行

if (info != null) {

//判断session是否已经失效(这一步在本文4.2中被执行)

if (info.isExpired()) {

// Expired - abort processing

if (logger.isDebugEnabled()) {

logger.debug("Requested session ID "

+ request.getRequestedSessionId() + " has expired.");

}

//执行登出操作

doLogout(request, response);

//从XML配置中的redirectSessionInformationExpiredStrategy获取URL重定向信息,页面跳转到登录页面

this.sessionInformationExpiredStrategy.onExpiredSessionDetected(new SessionInformationExpiredEvent(info, request, response));

return;

}

else {

// Non-expired - update last request date/time

sessionRegistry.refreshLastRequest(info.getSessionId());

}

}

}

chain.doFilter(request, response);

}

5、A处用户只能再次登录,这时B处用户session将会失效重登,如此循环

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/264518.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SQL server 系统优化--通过执行计划优化索引(1) (转)

SQL server 系统优化--通过执行计划优化索引&#xff08;1&#xff09; 前几天,远离上海&#xff0c;到了温州&#xff0c;在客户的这边处理系统慢&#xff0c;该系统每天正常down机7次左右&#xff0c;在线人员一多&#xff0c;系统运行缓慢&#xff0c;严重影响业务操作,到了…

Linux运维系统工程师系列---13

定制安装定制安装&#xff0c;也叫源码安装&#xff0c;需要自己编译源代码的安装方式步骤&#xff1a;1、解压源代码包2、配置 configure3、编译 make4、安装 make install接下来开始做实验&#xff0c;希望朋友们自己动手实践&#xff0c;有啥不清楚的可以直接提问我&#xf…

java system.setproperties_在JAVA中 System.getProperty 和 System.setProperty 方法.

今天着手研究TOMCAT源码.在刚開始的时候Startup类中init方法中调用非常多次System.getProperty和System.setProperty的方法.后来经过网上搜索才得知,这是对操作系统变量操作的方法.System还提供一个静态方法 System.getProperties(). 这种方法能够罗列出你系统的所有变量.调用S…

雷林鹏分享:XML 编码

XML 编码 XML 文档可以包含非 ASCII 字符&#xff0c;比如挪威语 &#xff0c;或者法语 。 为了避免错误&#xff0c;需要规定 XML 编码&#xff0c;或者将 XML 文件存为 Unicode。 XML 编码错误 如果您载入一个 XML 文档&#xff0c;您可以得到两个不同的错误&#xff0c;…

C#中理解接口以及接口的作用

在C#的开发中&#xff0c;接口是非常重要也非常好用的。可是很多时候很多人都不是很了解接口的做用&#xff0c;以及该如何使用。下面我们就来理解接口的作用&#xff0c;并看看如何使用吧。假设我们公司有两种程序员&#xff1a;VB程序员&#xff0c;指的是用VB写程序的程序员…

java开发中遇到的问题及解决方法(持续更新)

工作中&#xff0c;以C/C开发为主&#xff0c;难免与其他服务和Web进行交换&#xff0c;Java开发必不可少&#xff0c;又不想动用Eclipse大家伙&#xff0c;只能自己动手编写脚本进行Java代码的编译和运行&#xff0c;期间遇到的一些问题&#xff0c;记录下来供自己和大家参考。…

c语言转化java工具_详解C语言常用的一些转换工具函数

1、字符串转十六进制代码实现&#xff1a;void StrToHex(char *pbDest, char *pbSrc, int nLen){char h1,h2;char s1,s2;int i;for (i0; i{h1 pbSrc[2*i];h2 pbSrc[2*i1];s1 toupper(h1) - 0x30; //toupper 转换为大写字母if (s1 > 9)s1 - 7;s2 toupper(h2) - 0x30;if (…

vue项目使用eslint

转载自 https://www.cnblogs.com/hahazexia/p/6393212.html eslint配置方式有两种&#xff1a; 注释配置&#xff1a;使用js注释来直接嵌入ESLint配置信息到一个文件里配置文件&#xff1a;使用一个js&#xff0c;JSON或者YAML文件来给整个目录和它的子目录指定配置信息。这些配…

提里奥·弗丁(魔兽世界里的NPC)

弗丁的名字大家也许并不熟悉&#xff1b;但白银之手骑士团的大名&#xff0c;恐怕天下无人不识。作为白银之手骑士团创始人光明使者乌瑟尔的亲密友人&#xff0c;当年的弗丁是骑士团中地位最为崇高的圣骑士之一。在第二次战争中身先士卒的表现无愧白银之手的神圣之名。荣归故里…

java http请求插件_java http请求工具整理

处理了http 的get和post的请求&#xff0c;分别支持同步处理&#xff0c;异步处理两种方式下见代码。Slf4jpublic class HttpUtils { /** * 同步请求http请求 不推荐 * * param url * return */ public static byte[] httpGetSync(String url) { HttpGet httpGet new HttpGet(…

mysql存储过程语法及实例

2019独角兽企业重金招聘Python工程师标准>>> 存储过程如同一门程序设计语言&#xff0c;同样包含了数据类型、流程控制、输入和输出和它自己的函数库。 --------------------基本语法-------------------- 一.创建存储过程 create procedure sp_name() begin ......…

JAVA 重写重载/多态/抽象类/封装/接口/包

重写&重载 重写(override)是子类对父类的允许访问的方法的实现过程进行重新编写, 返回值和形参都不能改变。即外壳不变&#xff0c;核心重写&#xff01; 重载(overloading) 是在一个类里面&#xff0c;方法名字相同&#xff0c;而参数不同。返回类型可以相同也可以不同。 …

手写一个简单的WinForm程序(2)

经过高人指教之后的代码&#xff1a; using System; using System.Windows.Forms; using System.Drawing; namespace MyApplication { public partial class Form1 : Form { private delegate void ShowText(); TextBox textBox1 new TextBox(); …

mysql部署jar_mysql+jar踩坑记录

一、关于mysqlmysql 5用的驱动是com.mysql.jdbc.Drivermysql 6用的驱动是com.mysql.cj.jdbc.Drivermysql连接url中useUnicodetrue&characterEncodingutf8&serverTimezoneAsia/Shanghai作用useUnicodetrue&characterEncodingutf8—用来指定编码格式为utf8serverTime…

ajax和Java session监听

Session监听嘛&#xff0c;没什么好解释的&#xff0c;java提供了很灵活的事件机制来监听session&#xff0c;可以监听session的创建和销毁&#xff0c;监控session 所携带数据的创建、变化和销毁&#xff0c;可以监听session的锐化和钝化&#xff08;了解对象序列化的兄弟应该…

计算机历年考研复试上机基础题(一)

abc 题目描述 设a、b、c均是0到9之间的数字&#xff0c;abc、bcc是两个三位数&#xff0c;且有&#xff1a;abcbcc532。求满足条件的所有a、b、c的值。输入描述: 题目没有任何输入。 输出描述: 请输出所有满足题目条件的a、b、c的值。 a、b、c之间用空格隔开。 每个输出占一行。…

CSS选择器的权重与优先规则

2019独角兽企业重金招聘Python工程师标准>>> 我们在使用CSS对网页元素定义样式时经常会遇到这种情况&#xff1a;要对一般元素应用一般样式&#xff0c;然后在更特殊的元素上覆盖它们。那么我们怎么样来保证我们所新定义的元素样式能覆盖目标元素上原有的样式呢&…

《代码之美》第六章:菜鸟的自圆其说

Micheal Feather是我早就攻击过的专家级菜鸟&#xff0c;看过这一章&#xff0c;他在我心目中的高级初学者的形象&#xff0c;已经板上钉钉了。前两天看一本书&#xff0c;讲到调研表明&#xff0c;很多人在自己的领域干了20年&#xff0c;过了前五年&#xff0c;基本就不会再获…

java返回两个string_java – 为什么String.intern()方法返回两个不同的结果?

我有这样的代码&#xff1a;public static void main(String[] args) {String str1 new StringBuilder("计算机").append("软件").toString();System.out.println(str1.intern()str1);String str2 new StringBuilder("ja").append("va&qu…

列表和range、元组

1、listt.append&#xff08;&#xff09;默认追加在后面 2、list.insert&#xff08;索引&#xff0c;“元素”&#xff09;按索引添加 3、list.extend&#xff08;&#xff09;可添加多个字或字母的字符串&#xff0c;也可以是列表 4、list.pop&#xff08;&#xff09;默认删…