SpringBoot整合SpringSecurity,SESSION 并发管理,同账号只允许登录一次

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

SpringBoot整合SpringSecurity,SESSION 并发管理,同账号只允许登录一次

 

重写了UsernamePasswordAuthenticationFilter,里面继承AbstractAuthenticationProcessingFilter,这个类里面的session认证策略,是一个空方法,貌似RememberMe也是.

 

复制代码
public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean implements ApplicationEventPublisherAware, MessageSourceAware {
    protected ApplicationEventPublisher eventPublisher;
    protected AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
    private AuthenticationManager authenticationManager;
    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    private RememberMeServices rememberMeServices = new NullRememberMeServices();
    private RequestMatcher requiresAuthenticationRequestMatcher;
    private boolean continueChainBeforeSuccessfulAuthentication = false;
    private SessionAuthenticationStrategy sessionStrategy = new NullAuthenticatedSessionStrategy();
    private boolean allowSessionCreation = true;
    private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
    private AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();
复制代码
NullAuthenticatedSessionStrategy 源码
复制代码
public final class NullAuthenticatedSessionStrategy implements SessionAuthenticationStrategy {
    public NullAuthenticatedSessionStrategy() {
    }

    public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
    }
}
复制代码

 

所以必须自己配置一个session验证策略,以及配置并发控制.红字为关键

WebSecurityConfigurerAdapter 
复制代码
/**
 * Created by ZhenWeiLai on on 2016-10-16.
 * <p>
 * 三种方法级权限控制
 * <p>
 * 1.securedEnabled: Spring Security’s native annotation
 * 2.jsr250Enabled: standards-based and allow simple role-based constraints
 * 3.prePostEnabled: expression-based
 */
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private FilterInvocationSecurityMetadataSource securityMetadataSource;

    @Resource
    private SessionRegistry sessionRegistry;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/assets/**");
        web.ignoring().antMatchers("/components/**");
        web.ignoring().antMatchers("/css/**");
        web.ignoring().antMatchers("/images/**");
        web.ignoring().antMatchers("/js/**");
        web.ignoring().antMatchers("/mustache/**");
        web.ignoring().antMatchers("/favicon.ico");

        //注册地址不拦截
//        web.ignoring().antMatchers("/base/invoice/userinfo/u/reg");

//        web.ignoring().antMatchers("/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //解决不允许显示在iframe的问题
        http.headers().frameOptions().disable();

        http.addFilterAt(usernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
       //session并发控制过滤器
        http.addFilterAt(new ConcurrentSessionFilter(sessionRegistry,sessionInformationExpiredStrategy()),ConcurrentSessionFilter.class);
        //自定义过滤器
        //在适当的地方加入
        http.addFilterAt(filterSecurityInterceptor(securityMetadataSource, accessDecisionManager(), authenticationManagerBean()), FilterSecurityInterceptor.class);

        http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")).and().logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll().and().exceptionHandling().accessDeniedPage("/accessDenied");


        http.authorizeRequests().anyRequest().fullyAuthenticated();

        // 关闭csrf
        http.csrf().disable();


        /**
         * 以下配置无效
         */
        //session管理
        //session失效后跳转
//        http.sessionManagement().invalidSessionUrl("/login");
//        //只允许一个用户登录,如果同一个账户两次登录,那么第一个账户将被踢下线,跳转到登录页面
//        http.sessionManagement().maximumSessions(1).expiredUrl("/login");
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        // 自定义UserDetailsService,设置加密算法
        auth.userDetailsService(userDetailsService);
//.passwordEncoder(passwordEncoder())
        //不删除凭据,以便记住用户
        auth.eraseCredentials(false);
    }

    //session失效跳转
    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy() {
        return new SimpleRedirectSessionInformationExpiredStrategy("/login");
    }

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

    //SpringSecurity内置的session监听器
    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    private UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter() throws Exception {
        UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter = new CuzUsernamePasswordAuthenticationFilter();
        usernamePasswordAuthenticationFilter.setPostOnly(true);
        usernamePasswordAuthenticationFilter.setAuthenticationManager(this.authenticationManager());
        usernamePasswordAuthenticationFilter.setUsernameParameter("name_key");
        usernamePasswordAuthenticationFilter.setPasswordParameter("pwd_key");
        usernamePasswordAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/checkLogin", "POST"));
        usernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(simpleUrlAuthenticationFailureHandler());
        usernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
        //session并发控制,因为默认的并发控制方法是空方法.这里必须自己配置一个
        usernamePasswordAuthenticationFilter.setSessionAuthenticationStrategy(new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry));
        return usernamePasswordAuthenticationFilter;
    }

//    @Bean
//    public LoggerListener loggerListener() {
//        System.out.println("org.springframework.security.authentication.event.LoggerListener");
//        return new LoggerListener();
//    }
//
//    @Bean
//    public org.springframework.security.access.event.LoggerListener eventLoggerListener() {
//        System.out.println("org.springframework.security.access.event.LoggerListener");
//        return new org.springframework.security.access.event.LoggerListener();
//    }

    /**
     * 投票器
     */
    private AbstractAccessDecisionManager accessDecisionManager() {
        List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList();
        decisionVoters.add(new AuthenticatedVoter());
        decisionVoters.add(new RoleVoter());//角色投票器,默认前缀为ROLE_
        RoleVoter AuthVoter = new RoleVoter();
        AuthVoter.setRolePrefix("AUTH_");//特殊权限投票器,修改前缀为AUTH_
        decisionVoters.add(AuthVoter);
        AbstractAccessDecisionManager accessDecisionManager = new AffirmativeBased(decisionVoters);
        return accessDecisionManager;
    }

    @Override
    public AuthenticationManager authenticationManagerBean() {
        AuthenticationManager authenticationManager = null;
        try {
            authenticationManager = super.authenticationManagerBean();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return authenticationManager;
    }


    /**
     * 验证异常处理器
     *
     * @return
     */
    private SimpleUrlAuthenticationFailureHandler simpleUrlAuthenticationFailureHandler() {
        return new SimpleUrlAuthenticationFailureHandler("/getLoginError");
    }


//    /**
//     * 表达式控制器
//     *
//     * @return
//     */
//    private DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {
//        DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
//        return webSecurityExpressionHandler;
//    }

//    /**
//     * 表达式投票器
//     *
//     * @return
//     */
//    private WebExpressionVoter webExpressionVoter() {
//        WebExpressionVoter webExpressionVoter = new WebExpressionVoter();
//        webExpressionVoter.setExpressionHandler(webSecurityExpressionHandler());
//        return webExpressionVoter;
//    }

    // Code5  官方推荐加密算法
//    @Bean("passwordEncoder")
//    public BCryptPasswordEncoder passwordEncoder() {
//        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        return bCryptPasswordEncoder;
//    }

//    // Code3----------------------------------------------


    /**
     * 登录成功后跳转
     * 如果需要根据不同的角色做不同的跳转处理,那么继承AuthenticationSuccessHandler重写方法
     *
     * @return
     */
    private SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler() {
        return new SimpleUrlAuthenticationSuccessHandler("/loginSuccess");
    }


    /**
     * Created by ZhenWeiLai on on 2016-10-16.
     */

    private FilterSecurityInterceptor filterSecurityInterceptor(FilterInvocationSecurityMetadataSource securityMetadataSource, AccessDecisionManager accessDecisionManager, AuthenticationManager authenticationManager) {
        FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
        filterSecurityInterceptor.setSecurityMetadataSource(securityMetadataSource);
        filterSecurityInterceptor.setAccessDecisionManager(accessDecisionManager);
        filterSecurityInterceptor.setAuthenticationManager(authenticationManager);
        return filterSecurityInterceptor;
    }


}
复制代码

 

继承UsernamePasswordAuthenticationFilter ,注入SessionRegistry ,当用户登录验证成功后注册session

复制代码
/**
 * Created by ZhenWeiLai on 2017/6/2.
 */
public class CuzUsernamePasswordAuthenticationFilter  extends UsernamePasswordAuthenticationFilter {

    private boolean postOnly = true;

    @Resource
    private SessionRegistry sessionRegistry;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if(this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String username = this.obtainUsername(request);
            String password = this.obtainPassword(request);
            if(username == null) {
                username = "";
            }

            if(password == null) {
                password = "";
            }

            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            //用户名密码验证通过后,注册session
            sessionRegistry.registerNewSession(request.getSession().getId(),authRequest.getPrincipal());
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }
}
复制代码

重写用户实体类的比较方法.

复制代码
    /**
     * 重写比较方法,SpringSecurity根据用户名来比较是否同一个用户
     */
    @Override
    public boolean equals(Object o){
        if(o.toString().equals(this.username))
            return true;
        return false;
    }

    @Override
    public int hashCode(){
        return username.hashCode();
    }


    @Override
    public String toString() {
        return this.username;
    }
复制代码
SpringBoot整合SpringSecurity与SSH:构建企业级安全应用骨架实战 在构建现代企业级应用时,权限控制与安全传输是保障系统安全的两大基石。权限控制基于RBAC(基于角色的访问控制)模型,通过用户、角色、权限的关联,实现从菜单到按钮的精细化访问管理,其核心原理在于前后端协同校验,前端负责体验优化,后端通过注解拦截器进行强制校验,构筑了完整的防护体系。安全传输则利用SSH协议,通过公钥认证和加密隧道,为管理接口或服务间通信提供点对点的安全保障,有效提升了内网应用的安全水位。这两项技术的结合,为后台管理系统、运营平台等高敏感度应用场景提供了从身份认证、访问控制到数据传输的全链路安全 阅读详情

相关推荐

Spring Boot Security 2.5.8 实现账号、手机号、邮件登录,记住密码等功能

基于Spring Boot Security 2.5.8,扩展了核心功能,支持用户名,手机号,邮箱登录,以及记住密码,JWT等功能。有完整的数据库脚本及功能演示。

SpringSecurity OAuth2过滤器源码解读。

chain.doFilter源码。2,当用户访问时,比如(/oauth/token)uri时,第一个拦截的filter是ClientCredentialsTokenEndpointFilter,而拦截的方法,在其父类AbstractAuthenticationProcessingFilter的doFilter方法中。3,requiresAuthentication(request,response)方法,该方法主要是进行uri路径的匹配,只有当访问的uri是/oauth/token时,才会返回true。..

weixin_45111933的博客 2739

NXP S32K3 Safety软件生态全解析:RTD、SPD、SAF、SCST到底怎么选?

本文深入解析NXP S32K3系列MCU的安全软件生态,详细对比RTD、SPD、SAF和SCST四大组件的功能定位与选型策略。针对不同ASIL等级需求,提供从架构设计到工程实践的完整解决方案,帮助开发者高效实现功能安全认证,优化汽车电子系统的安全性与可靠性。

weixin_42524226的博客 324

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

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.spring.

java_fisher的博客 2046

嵌入式硬件实战:RC、LC与RL滤波电路的设计与选型指南

本文深入探讨了嵌入式系统中RC、LC与RL滤波电路的设计与选型策略。通过生活化比喻和实战案例,详细解析了三种滤波电路的工作原理、应用场景及工程注意事项,帮助工程师根据电流大小、频率特征和成本预算选择最优方案,提升嵌入式硬件设计的稳定性和抗干扰能力。

kiwi8的博客 286

整车无线布置的综述

车载无线功能日益丰富,涵盖5G、GNSS、V2X等多种技术,布置需兼顾性能与美观。车顶是理想位置,鲨鱼鳍、后视镜等集成方案可优化空间。需考虑射频电缆损耗、GNSS天线视角、V2X全向覆盖等关键因素。整车测试需适应高频段需求,通过链路预算和互补天线设计优化信号。不同车型需定制方案,并注意抗干扰和多频段兼容性。(149字)

Godspeed_zwh的博客 1861

SpringBoot使用SpringSecurity的session管理

文章目录session管理session超时处理session并发控制(一个账号只在一个平台登录)集群session管理 session管理 session超时处理 直接在配置文件配置 server: servlet: session: timeout: 10 SpringBoot的默认的session过期时间最少为1分钟。session失效跳转地址,在security配...

taojin12的博客 2493

InsightFace实战:如何在树莓派上部署轻量级人脸识别系统(附完整代码)

本文详细介绍了如何在树莓派上部署基于InsightFace框架的轻量级人脸识别系统。通过硬件选型、环境配置、模型优化(如MobileFaceNet)及完整代码实战,指导开发者构建本地化、低功耗的智能应用,如智能门铃,并提供了性能调优与系统服务化的进阶技巧。

weixin_29043895的博客 352

SpringBoot整合SpringSecurity(附带源码)

SpringBoot整合SpringSecurity配置环境配置idea配置thymeleaf配置JPA配置数据库配置包目录配置dao层配置Entity关系SpringSecurity配置配置拦截策略自定义登陆账号验证配置自定义权限验证 配置环境 配置idea 我使用的是idea,点击New Project 点击next项目信息配置随意,再下一步选上下图所示的组件 配置thymeleaf 在po...

Coder Wang 6566

ArcGIS 10.8软件安装包免费下载及安装教程

ArcGIS 10.8安装教程

qq_44894692的博客 2万+

保姆级教程:用再生龙Clonezilla Live给Ubuntu系统做全盘备份与恢复(含BIOS设置避坑)

本文提供了一份详细的Clonezilla Live教程,指导Ubuntu用户如何轻松完成全盘备份与恢复。从启动盘制作、BIOS设置避坑到备份参数解析和恢复操作,涵盖了所有关键步骤和常见问题解决方案,帮助用户高效保护系统数据。

weixin_42116058的博客 646

SpringBoot + SpringSecurity+JWT整合(微服务适用)

SpringSecurity基于表单的登录认证流程如下图: 大致过程是在UsernamePasswordAuthenticationFilter将username和password封装成UsernamePasswordAuthenticationToken,之后会在AuthenticationProvider(接口,需要自己实现)的authenticate方法中拿到且校验(一般是查数据库,对比账号密码),而校验成功则返回Authentication接口对象(一般情况是直接返回UsernamePassw

weixin_42372860的博客 1514

ansys命令流力磁耦合仿真

文章目录前言一、力磁耦合仿真流程二、静力学仿真三、力磁耦合模型构建四、静磁学仿真总结 前言 一、力磁耦合仿真流程 力磁耦合有限元仿真流程中,首先进行静力学仿真,经过前处理模块、分析计算模块和后处理模块提取三维模型单元应力,然后根据力磁耦合方程中,通过matlab将单元应力导入到磁导率与应力的关系式中,得到单元的相对磁导率。最后采用载荷传递耦合方式,进行静磁学模拟仿真,分析计算得到该载荷下试件的磁场分布。,如下图所示为力磁耦合仿真流程图: 二、静力学仿真 下图为中心预制条形缺陷的Q235钢板试..

wsfwsf128的博客 2663

SpringBoot,Security4, redis共享session,分布式SESSION并发控制,同账号只能登录一次

原文:https://www.cnblogs.com/sweetchildomine/p/7007242.html 由于集成了spring session ,redis 共享session,导致SpringSecurity单节点的session并发控制失效, springSession 号...

695

搭建自己的MQTT服务器,实现设备上云(Ubuntu+EMQX)

这篇文章教大家在ECS云服务器上部署EMQX,搭建自己私有的MQTT服务器,配置EMQX实现设备上云,设备数据转发,存储;服务器我采用的华为云的ECS服务器,系统选择Ubuntu系统。

2万+

深度学习工具包 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")

SpringBoot系列——Security + Layui实现一套权限管理后台模板

  前言   Spring Security官网:https://spring.io/projects/spring-security   Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架,侧重于为Java应用程序提供身份验证和授权。   本文记录在SpringBoot项目中整合Spring Security进行权限控制,配合Layui,实现一套相对...

weixin_30802171的博客 1089

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

springBoot2.X+spring security5.3.8+redis整合用户登录权限控制

springBoot2.X+spring security5.3.8+redis整合用户登录权限控制主要功能点介绍重要代码片段 主要功能点介绍 1.权限过滤 2.改造attemptAuthentication,重写该方法目的在于支持JSON格式提交登录信息。 3.验证后的返回信息均实现相应接口重写相应方法,以JSON格式返回前端。 4.会话管理,session并发控制过滤器,限制同一账号同时登录数量。 5.针对集群部署场景,通过redis实现session共享。 重要代码片段 package com.hex

architecture_upper的博客 459

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

SpringBoot+SpringSecurity之多模块用户认证授权同步

在之前的文章里介绍了SpringBoot和SpringSecurity如何继承。之后我们需要考虑另外一个问题:当前微服务化也已经是大型网站的趋势,当我们的项目采用微服务化架构时,往往会出现如下情况: 首先,我们会建立一个用户中心UserCenter,实现用户的登录、登出以及其他用户信息维护等相关功能。 然后,我们会有其他业务模块,比如订单中心OrderCenter,用来创建、删除及查看订单...

weixin_30598225的博客 1339

SpringBoot - Spring Security详解(一)

Spring Security 是一种基于Spring AOP、Servlet过滤器的、相对复杂的安全管理框架,功能比 Shiro 更加强大,权限控制细粒度更高,对 OAuth 2 的支持也更友好。它同时在WEB请求和方法调用时处理身份确认和授权。由于 Spring Security 源自 Spring 家族,因此可以和 Spring 框架无缝整合,在Spring Boot 中提供了自动化的配置方案,可以让 Spring Security 的使用更加便捷。...

记录并分享 524

springsecurity mysql_肝到头秃!阿里爆款的顶配版Spring Security笔记

Spring Security Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。由于它是Spring生态系统中的一员,因此它伴随着整个Spring生态系统不断修正、升级,在spring boot项目中加入springsecurity更是十分简单,使用Spring Security 减少了为企业系统安全控制编写大量重复代码的工作。S...

weixin_39758048的博客 139

阿里巴巴顶配版Spring Security OAuth2.0认证授权全彩笔记限时开源

首先,SSM环境中我们通过xml配置的方式,从源码渗入开始,完成Spring Security基本的“认证”和“授权”功能讲解,其中还会融合“记住我”,CSRF拦截等技术。OAuth(开放授权)是一个开放标准,允许用户授权第三方移动应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,OAuth2.0是OAuth协议的延续版本,但不兼容OAuth 1.0(即完全废止了OAuth1.0)。方面的资料相对来说比较并且并不完善,

m0_50180963的博客 147

阿里爆款的顶配版Spring Security OAuth2.0认证授权全彩笔记震撼来袭

首先,SSM环境中我们通过xml配置的方式,从源码渗入开始,完成Spring Security基本的“认证”和“授权”功能讲解,其中还会融合“记住我”,CSRF拦截等技术。OAuth(开放授权)是一个开放标准,允许用户授权第三方移动应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,OAuth2.0是OAuth协议的延续版本,但不兼容OAuth 1.0(即完全废止了OAuth1.0)。方面的资料相对来说比较并且并不完善,

m0_50180963的博客 161

阿里独家推出,顶配版Spring Security笔记,让你迅速掌握安全框架的核心

Spring Security是一个专门为基于Spring的企业应用系统提供声明式安全访问控制解决方案的安全框架。作为Spring生态系统中的重要一员,它不断随着整个生态系统的更新而修正和升级。在Spring Boot项目中集成Spring Security非常简单,这大大减少了为企业系统安全控制编写大量重复代码的工作。通过Spring Security,开发者可以更加专注于业务逻辑,而将安全控制交给框架来完成,从而提高了开发效率和安全性。

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

阿里爆款顶配版Spring Security笔记,让你轻松掌握安全框架的精髓

Spring Security是一个专门为基于Spring的企业应用系统提供声明式安全访问控制解决方案的安全框架。作为Spring生态系统中的重要一员,它不断随着整个生态系统的更新而修正和升级。在Spring Boot项目中集成Spring Security非常简单,这大大减少了为企业系统安全控制编写大量重复代码的工作。通过Spring Security,开发者可以更加专注于业务逻辑,而将安全控制交给框架来完成,从而提高了开发效率和安全性。

资料免费分享,点击名片 835
上一篇: spring boot 整合 spring security 之使用数据库验证
codes520
博客等级 码龄9年 2粉丝 0原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值