spring-security 是怎么实现同一个用户登录次数限制的(包含源码分析)

spring security的session管理 1 spring security的session管理 spring security关于认证session的逻辑处理在接口SessionAuthenticationStrategy的onAuthentication方法中,先看看这个接口和其实现类。 1.1 SessionAuthenticationStrategy接口 public interface SessionAuthenticationStrategy { /** * 当一个认证生成之后处理sessio 阅读详情

先上一张流程图


主要配置源码:
package com.example.demo.sms;

import com.example.demo.core.AbstractSecurityConfigurerAdapter;
import com.example.demo.core.MySimpleRedirectSessionInformationExpiredStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.session.ConcurrentSessionFilter;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Configuration
public class SmsLoginConfig extends AbstractSecurityConfigurerAdapter {

    @Resource
    private SessionRegistry sessionRegistry;


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private  AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;


    @Override
    public void configure(HttpSecurity http) throws Exception {

       SmsAuthenticationProcessingFilter processingFilter = new SmsAuthenticationProcessingFilter("/sms/login");
        processingFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        processingFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        processingFilter.setAuthenticationManager(authenticationManager);


        //注册新session策略
        RegisterSessionAuthenticationStrategy registerSessionAuthenticationStrategy = new RegisterSessionAuthenticationStrategy(sessionRegistry);
        registerSessionAuthenticationStrategy = postProcess(registerSessionAuthenticationStrategy);

        //session 管理策略,
        ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlStrategy = new ConcurrentSessionControlAuthenticationStrategy(
                sessionRegistry);


        // -------------一个用户登录一次设置  start--------------------------
        //设置 限制的同一个用户登录的次数
        concurrentSessionControlStrategy.setMaximumSessions(1);
        //作用是当session超过次数限制时,是当前用户无法登陆,还是之前登录过期的策略设置,默认是之前过期
        concurrentSessionControlStrategy.setExceptionIfMaximumExceeded(false);
        List<SessionAuthenticationStrategy> delegateStrategies = new ArrayList<>();
        delegateStrategies.addAll(Arrays.asList(concurrentSessionControlStrategy,registerSessionAuthenticationStrategy));
        //compositeSessionAuthenticationStrategy是存放SessionAuthenticationStrategy的集合
        CompositeSessionAuthenticationStrategy compositeSessionAuthenticationStrategy = new CompositeSessionAuthenticationStrategy(delegateStrategies);

        //设置 session 策略
        processingFilter.setSessionAuthenticationStrategy(compositeSessionAuthenticationStrategy);

        //ConcurrentSessionFilter的作用是判断session是否过期,如果过期就执行过期方法(是requst中的session无效,清除凭证)
        http.addFilterAt(new ConcurrentSessionFilter(sessionRegistry,new SimpleRedirectSessionInformationExpiredStrategy()), ConcurrentSessionFilter.class);

        // -------------一个用户登录一次设置  end--------------------------

        http.addFilterBefore(processingFilter, UsernamePasswordAuthenticationFilter.class);

        //MyAuthenticationProvider 真正认证
        http.authenticationProvider(new SmsAuthenticationProvider());
    }

   @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }


}

 

 

介绍下各个类的作用:

ConcurrentSessionFilter:是判断session是否过期,如果过期就执行过期方法
SessionRegistryImpl:存放认证通过的session消息
concurrentSessionControlStrategy:判断是否超过设置的session限制
registerSessionAuthenticationStrategy:注册新session
CompositeSessionAuthenticationStrategy:存放上两个策略
关键源码如下,如果有不懂可以提问。
1.设置策略。可以通过自定义实现类AbstractAuthenticationProcessingFilter#setSessionAuthenticationStrategy方法设置策略

   public void setSessionAuthenticationStrategy(
         SessionAuthenticationStrategy sessionStrategy) {
      this.sessionStrategy = sessionStrategy;
   }
   
   
入口方法(认证成功会掉调用):
AbstractAuthenticationProcessingFilter#sessionStrategy.onAuthentication(authResult, request, response);

# CompositeSessionAuthenticationStrategy 是个可以存放多个sessionStrategy的封装类
CompositeSessionAuthenticationStrategy存放两个策略concurrentSessionControlStrategy,registerSessionAuthenticationStrategy会循环调用,顺序不能变
   public void onAuthentication(Authentication authentication,
         HttpServletRequest request, HttpServletResponse response)
               throws SessionAuthenticationException {
      #遍历每个sessionStrategy执行onAuthentication方法,
      #我的配置中设置了两个策略concurrentSessionControlStrategy,registerSessionAuthenticationStrategy,
      #并且构造方法都用了同一个SessionRegistryImpl
      for (SessionAuthenticationStrategy delegate : this.delegateStrategies) {
         if (this.logger.isDebugEnabled()) {
            this.logger.debug("Delegating to " + delegate);
         }
         delegate.onAuthentication(authentication, request, response);
      }
   }



   两个策略concurrentSessionControlStrategy,registerSessionAuthenticationStrategy的关键源码如下:
   //ConcurrentSessionControlAuthenticationStrategy作用:判断当前登录用户名所存在的session是否在允许的最大登录数内,如果是直接返回,否就会执行
   //registerSessionAuthenticationStrategy 注册新session


   concurrentSessionControlStrategy类执行如下,
   public void onAuthentication(Authentication authentication,
             HttpServletRequest request, HttpServletResponse response) {

          final List<SessionInformation> sessions = sessionRegistry.getAllSessions(
                authentication.getPrincipal(), false);

          int sessionCount = sessions.size();
          #可以通过 concurrentSessionControlStrategy.setMaximumSessions(1)改变同一用户登录次数
          int allowedSessions = getMaximumSessionsForThisUser(authentication);

          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) {
             HttpSession session = request.getSession(false);

             if (session != null) {
                // Only permit it though if this request is associated with one of the
                // already registered sessions
                //第一次登录会执行如下方法,因为是同一个sessionId
                for (SessionInformation si : sessions) {
                   if (si.getSessionId().equals(session.getId())) {
                      return;
                   }
                }
             }
             // If the session is null, a new one will be created by the parent class,
             // exceeding the allowed number
          }

            //如果超过设置,就会执行sessions是之前该用户登录的session集合,allowableSessions是运行的个数,registry是SessionRegistryImpl,第二次登录会调用
          allowableSessionsExceeded(List<SessionInformation> sessions,
                     int allowableSessions, SessionRegistry registry)

       }




          protected void allowableSessionsExceeded(List<SessionInformation> sessions,
                 int allowableSessions, SessionRegistry registry)
                 throws SessionAuthenticationException {
                 }
              //属性exceptionIfMaximumExceeded是决定如果登录超过限制,是限制当前登录用户异常,还是将之前登录用户强制退出策略(默认是false),
              if (exceptionIfMaximumExceeded || (sessions == null)) {
                 throw new SessionAuthenticationException(messages.getMessage(
                       "ConcurrentSessionControlAuthenticationStrategy.exceededAllowed",
                       new Object[] {allowableSessions},
                       "Maximum sessions of {0} for this principal exceeded"));
              }

              // Determine least recently used sessions, and mark them for invalidation
              sessions.sort(Comparator.comparing(SessionInformation::getLastRequest));
              int maximumSessionsExceededBy = sessions.size() - allowableSessions + 1;
              List<SessionInformation> sessionsToBeExpired = sessions.subList(0, maximumSessionsExceededBy);
              for (SessionInformation session: sessionsToBeExpired) {
                  //超过的session就设置为无效
                 session.expireNow();
              }
           }


   RegisterSessionAuthenticationStrategy作用是增加新sessionInfo
      public void onAuthentication(Authentication authentication,
             HttpServletRequest request, HttpServletResponse response) {
             
          sessionRegistry.registerNewSession(request.getSession().getId(),
                authentication.getPrincipal());
       }

       SessionRegistryImpl
       registerNewSession(String sessionId, Object principal) {
              Assert.hasText(sessionId, "SessionId required as per interface contract");
              Assert.notNull(principal, "Principal required as per interface contract");

              if (getSessionInformation(sessionId) != null) {
                 removeSessionInformation(sessionId);
              }

              if (logger.isDebugEnabled()) {
                 logger.debug("Registering session " + sessionId + ", for principal "
                       + principal);
              }

                //放置sessionId-SessionInformation(principal, sessionId, new Date())
              sessionIds.put(sessionId,
                    new SessionInformation(principal, sessionId, new Date()));

                //放置principal--sessionIds
              principals.compute(principal, (key, sessionsUsedByPrincipal) -> {
                 if (sessionsUsedByPrincipal == null) {
                    sessionsUsedByPrincipal = new CopyOnWriteArraySet<>();
                 }
                 sessionsUsedByPrincipal.add(sessionId);

                 if (logger.isTraceEnabled()) {
                    logger.trace("Sessions used by '" + principal + "' : "
                          + sessionsUsedByPrincipal);
                 }
                 return sessionsUsedByPrincipal;
              });
           }

    SessionRegistryImpl 部分源码
    public class SessionRegistryImpl implements SessionRegistry,
          ApplicationListener<SessionDestroyedEvent> {

       // ~ Instance fields
       // ================================================================================================

       protected final Log logger = LogFactory.getLog(SessionRegistryImpl.class);

        #存放的key是用户名 ,value 是 sessionId集合
       private final ConcurrentMap<Object, Set<String>> principals;

       private final Map<String, SessionInformation> sessionIds;


       public SessionRegistryImpl() {
          this.principals = new ConcurrentHashMap<>();
          this.sessionIds = new ConcurrentHashMap<>();
       }




        //ConcurrentSessionFilter源码:判断是否过期,如果过期执行过期方法,如果没有过期刷新请求时间
       public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
             throws IOException, ServletException {
          HttpServletRequest request = (HttpServletRequest) req;
          HttpServletResponse response = (HttpServletResponse) res;

          HttpSession session = request.getSession(false);

          if (session != null) {
          //根据sessionId去获取SessionInformation
             SessionInformation info = sessionRegistry.getSessionInformation(session
                   .getId());

             if (info != null) {
             //判断是否过期,只有登录次数限制才设置了过期,所以一定是其他设备上登录导致的过期
                if (info.isExpired()) {
                   // Expired - abort processing
                   if (logger.isDebugEnabled()) {
                      logger.debug("Requested session ID "
                            + request.getRequestedSessionId() + " has expired.");
                   }
                   //设置了tomcat的session失效,清除凭证
                   doLogout(request, response);

                        //回调过期处理方法,可以自定义,该类构造方法就可以自定义设置
                   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);
       }
Spring Security 自定义登录Session配置 有这样一个需求,一个账号只能在一个客户端浏览器上登录,如果同样的账号在别的客户端浏览器上登录的话,之前的登录需要被踢下去 阅读详情

相关推荐

spring boot使用spring security 的基本配置 以及 限制同一账号不能多处登录

关于如何spring boot 整合spring security 请自行百度,这里只是简单描述spring security 的配置项。  @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true)// 启用 Spring Security 全局方法 //prePostEnabled...

weixin_40340362的博客 2205

spring security自定义登录授权过滤器限制同一账号同时在线数量

摘要:本文主要目的是解决spring security在使用自定义登录授权过滤器时,在protected void configure(final HttpSecurity http)方法中设置maximumSessions属性不生效的问题。本文只是进行了粗略的思路,包含主要的代码片段,并非完整的业务代码,仅供参考。

L_D_W的博客 2636

Spring Security 详解

用户认证通过后,为了避免用户的每次操作都进行认证可将用户的信息保证在会话中。会话就是系统为了保持当前用户的登录状态所提供的机制,常见的有基于session方式、基于token方式等。

As_Yua的博客 1万+

Spring Security之Session管理

对于UsernamePasswordAuthenticationFilter而言,SessionManagementFilter有点名不副实,因为前者登录成功后就会自己调用SessionAuthenticationStrategy。因此学习session管理,我们的重点是SessionAuthenticationStrategy。

Evan_L的博客 2966

Re:从零开始的Spring Security Oauth2(一)

前言今天来聊聊一个接口对接的场景,A厂家有一套HTTP接口需要提供给B厂家使用,由于是外网环境,所以需要有一套安全机制保障,这个时候oauth2就可以作为一个方案。关于oauth2,其实是一个规范,本文重点讲解spring对他进行的实现,如果你还不清楚授权服务器,资源服务器,认证授权等基础概念,可以移步理解OAuth 2.0 - 阮一峰,这是一篇对于oauth2很好的科普文章。 需要对spring

徐靖峰的专栏 8万+

Spring Security 完整教程

Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架。它是基于 Java EE 的企业级安全解决方案的事实标准。Spring Security 提供了完整的安全解决方案,主要功能模块如下: 主要功能详解 1. 认证(Authentication) 功能作用:验证用户身份,确认"你是谁"解决的问题:具体功能:功能作用:控制已认证用户的访问权限,决定"你能做什么"解决的问题:具体功能:功能作用:防御常见的 Web 安全攻击解决的问题:具体功能:功能作用:管理用户会话生命周期和并发访

翱翔-蓝天 172

java中限制多人登录的_Spring Boot + Spring Security 防止用户在多处同时登录(一个用户同时只能登录一次)及源码分析...

网上很多文章的实现方法写得比较复杂这里介绍一个简单的方法。实现@Configuration@EnableWebSecuritypublic class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exce...

weixin_39923806的博客 2258

使用WSL2安装ubuntu系统并配置深度学习环境

wsl2安装ubuntu部署深度学习环境的方法

u013358093的博客 2701

Spring Boot + Spring Security 防止用户在多处同时登录(一个用户同时只能登录一次)及源码分析

Spring Boot + Spring Security 防止用户在多处同时登录(一个用户同时只能登录一次)及源码分析,网上很多文章的实现方法写得比较复杂 ,这里介绍一个简单的方法。

杰明Jamin的博客 4万+

第182期 Claude Skills:深入探究Anthropic的智能体框架(一篇彻底讲透彻)

摘要: Claude Skills是Anthropic推出的智能体框架,通过连接外部工具和服务扩展Claude AI的功能,支持实时交互与任务执行。其核心架构包含技能路由器、注册表、执行引擎等模块,采用渐进式披露机制优化上下文管理。与MCP和A2A相比,Skills更注重模块化设计与Claude深度集成,通过SKILL.md文件定义可重复工作流程,兼具高效性和灵活性。开发者可创建自定义技能,遵循聚焦用户价值、安全隐私等最佳实践,实现AI能力的场景化拓展。该框架与MCP、A2A形成互补,共同推动智能体生态发展

全网120W+关注AI拉呱,专注人工智能以及科技前沿! 2132

GDB交叉编译与问题解决:从零到精通的深度指南

完成后,GDB会安装到/usr/local/gdb-aarch64/bin,可以用aarch64-linux-gnu-gdb --version检查。:得有支持目标架构的交叉编译工具链,比如gcc-arm-none-eabi(用于ARM裸机)或aarch64-linux-gnu-gcc(用于ARM Linux)。:在配置工具链时,运行aarch64-linux-gnu-gcc --version检查版本,确保工具链没问题。这种场景下用GDB调试,就像在荒野求生,但别慌,GDB依然是你的好伙伴。

大模型大数据攻城狮的专栏 1万+

九、Spring Security 防止用户在多处同时登录(一个用户同时只能登录一次)及源码分析

参见Spring Boot + Spring Security 防止用户在多处同时登录(一个用户同时只能登录一次)及源码分析

panchang199266的博客 9322

踩过20+工控视觉项目的坑后,我用C# + 海康相机 + YOLOv11实现了零依赖产线缺陷检测

触发式检测:只有光电传感器检测到零件到位,才触发相机拍照和算法检测,不是持续推理,减少工控机性能占用;全链路本地运行:从图像采集、算法推理到不良品剔除,所有逻辑全在本地工控机运行,不需要外网、不需要云端服务,哪怕产线断网也能正常运行;异常降级机制:算法推理异常时,系统自动触发产线缓停,同时声光告警,不会让不良品流到下工序,满足汽车行业IATF16949质量要求;模块化解耦:算法核心层和业务逻辑层完全分离,后续更换YOLO模型、新增缺陷类型,只需要替换模型文件,不需要修改业务逻辑;全链路可追溯。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 152

Spring Security 自动踢掉前一个登录用户,一个配置搞定!,网易前端社招面经

maximumSessions 表示配置最大会话数为 1,这样后面的登录就会自动踢掉前面的登录。这里其他的配置都是我们前面文章讲过的,我就不再重复介绍,文末可以下载案例完整代码。配置完成后,分别用 Chrome 和 Firefox 两个浏览器进行测试(或者使用 Chrome 中的多用户功能)。Chrome 上登录成功后,访问 /hello 接口。Firefox 上登录成功后,访问 /hello 接口。

2401_87715696的博客 1192

OpenCloudOS9操作系统搭建Confluence8.2.1+Jira企业级WIKI

Atlassian Confluence是一个专业的企业知识管理与协同软件,可用于构建企业wiki

背锅神童的博客 1023

2026星宸科技数字IC设计笔试带答案

摘要:本文包含四个计算机科学领域的编程与逻辑设计题目解析。第一部分通过C语言程序补充水仙花数判断代码,考查循环结构和函数设计;第二部分分析Verilog代码的D触发器电路,讨论时序约束与时钟频率影响;第三部分详细讲解静态时序分析中的建立/保持时间计算与违例判断;第四部分计算机体系结构题目涉及CPI、MIPS计算和性能加速比分析。最后还包含一个逻辑代数化简的示例,展示基本的布尔代数简化技巧。这些题目全面覆盖了编程基础、数字电路设计、时序分析和计算机性能评估等核心知识点。(149字)

Open 121

【Spring-Security源码分析】AuthenticationManagerBuilder

1、继承结构类图 AuthenticationManagerBuilder用于创建AuthenticationManager。 允许轻松构建内存身份验证,LDAP身份验证,基于JDBC的身份验证,添加UserDetailsService以及添加AuthenticationProvider。 public interface SecurityBuilder<O> { /*...

通往神秘的道路的专栏 1万+

015、架构_配置文件_管理节点(proxymanager.ini)

该配置文件中的参数在后台配置,两种生效方式:*所有参数重启生效。*部分参数可以使用工具dbtool动态生效。动态生效命令为:dbtool-pm-load-config。配置文件“proxymanager.ini”用于设置元数据管理模块的信息。文件路径为“~/etc”。配置文件“proxymanager.ini”是普通的文本文件。默认值proxymanager-alarmconfutf8.txt。配置错误或不配置,PM无法连接MDS,无法服务。获取元数据失败超时处理时间。异常时请求启动对等回滚。

Oracle/MySQL 到 国产信创数据库|迁移 · 调优 · 信创替换 329

Spring Security系列教程15--基于散列加密方案实现自动登录

前言 在前面的2个章节中,一一哥 带大家实现了在Spring Security中添加图形验证码校验功能,其实Spring Security的功能不仅仅是这些,还可以实现很多别的效果,比如实现自动登录,注销登录等。 有的小伙伴会问,我们为什么要实现自动登录啊?这个需求其实还是很常见的,因为对于用户来说,他可能经常需要进行登录以及退出登录,你想想,如果用户每次登录时都要输入自己的用户名和密码,是不是很烦,用户体验是不是很不好? 所以为了提高项目的用户体验,我们可以在项目中添加自动登录功能,当然也要给用户提

一一哥 1215

YOLO11改进:轻量级改进 | 通用倒瓶颈(UIB)搜索块结合C3k2二次创新 | 轻量化之王MobileNetV4

通用倒瓶颈(UIB)搜索块替代YOLO11的C3k2

会AI的学姐 293

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring Security(四) —— 核心过滤器源码分析

摘要: 原创出处https://www.cnkirito.moe/spring-security-4/「老徐」欢迎转载,保留摘要,谢谢! 4 过滤器详解 前面的部分,我们关注了Spring Security是如何完成认证工作的,但是另外一部分核心的内容:过滤器,一直没有提到,我们已经知道Spring Security使用了springSecurityFilterChain作为了...

weixin_30668887的博客 99

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Spring Security Oauth2 permitAll()还校验token

前言 上周五有网友问道,在使用spring-security-oauth2时,虽然配置了.antMatchers("/permitAll").permitAll(),但如果在header 中 携带 Authorization Bearer xxxx,OAuth2AuthenticationProcessingFilter还是会去校验Token的正确性,如果Token合法,可以正常访问,否则,请求失...

weixin_39047791的博客 4331

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

10、spring security拦截器之UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter:登录验证 在SecurityConfig中对应: http.formLogin() //表单登录 .loginPage("/login.html") //登录页面 .loginProcessingUrl("/login") //登录的url,默认:/login .usernameParameter("username") //用户名参数名称,默认:username

u012153127的博客 1054

珍贵资料:阿里内部Spring Security实战指南,邀您一同开启安全之旅

第1章 给大家简单的介绍Spring Security,创建了一个简单的Spring Security项目,带领大家初步领略Spring Security带来的便利。第2章 我们使用表单认证来保护URL资源。第3章 将更加深入地对Spring Security 进行配置,且初步使用授权机制。在验证用户名和密码之前,引入辅助验证可有效防范暴力试错,图形验证码就是简单且行之有效的一种辅助验证方式。本章将使用过滤器和自定义认证两种方式实现图形验证码功能。第5章 主要讲。

资料免费分享,点击名片 951

Spring Security源码分析(一)

Spring Security源码分析<一> SpringSecurity基本原理是基于一个过滤器链 我们启动一个SpringSecurity项目,日志会打印过滤器 一共有十二个过滤器,大致介绍一下 WebAsyncManagerIntegrationFilter将Security上下文与Spring Web中用于处理异步请求映射的 WebAsyncManager 进行集成 Se...

ymbcxb 325
上一篇: nginx 根据cookie分流 配置文件
Fisher1229
博客等级 码龄9年 6粉丝 10原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值