WebSecurityConfigurerAdapter

WebSecurityConfigurerAdapter详解 本文来详细说下security中的WebSecurityConfigurerAdapter 文章目录概述 概述 阅读详情

Hello Web Security

在这个部分,我们对一个基于web的security作一些基本的配置。可以分成四个部分:

WebSecurityConfigurerAdapter

@EnableWebSecurity注解以及WebSecurityConfigurerAdapter一起配合提供基于web的security。继承了WebSecurityConfigurerAdapter之后,再加上几行代码,我们就能实现以下的功能:

  • 要求用户在进入你的应用的任何URL之前都进行验证
  • 创建一个用户名是“user”,密码是“password”,角色是“ROLE_USER”的用户
  • 启用HTTP Basic和基于表单的验证
  • Spring Security将会自动生成一个登陆页面和登出成功页面
1
2
3
4
5
6
7
8
9
10
@Configuration
@EnableWebSecurity
public class HelloWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
 
@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) {
auth.inMemoryAuthentication()
.withUser( "user" ).password( "password" ).roles( "USER" );
}
}

作为参考,我们在这里也给出相似的XML配置,不过有几个特殊配置:

  • Spring Security会生成一个登陆页面,验证失败页面和登出成功页面
  • login-processing-url仅仅处理HTTP POST
  • login-page仅仅通过HTTP GET进入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
< http use-expressions = "true" >
   < intercept-url pattern = "/**" access = "authenticated" />
   < logout
     logout-success-url = "/login?logout"
     logout-url = "/logout"
   />
   < form-login
     authentication-failure-url = "/login?error"
     login-page = "/login"
     login-processing-url = "/login"
     password-parameter = "password"
     username-parameter = "username"
   />
</ http >
< authentication-manager >
   < authentication-provider >
     < user-service >
       < user name = "user"
           password = "password"
           authorities = "ROLE_USER" />
     </ user-service >
   </ authentication-provider >
</ authentication-manager >

AbstractAnnotationConfigDispatcherServletInitializer

下一步就是保证ApplicationContext包含我们刚刚定义的HelloWebSecurityConfiguration。有几种方法都可行,我们这里使用Spring的AbstractAnnotationConfigDispatcherServletInitializer:

1
2
3
4
5
6
7
8
9
public class SpringWebMvcInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
 
@Override
protected Class[] getRootConfigClasses() {
return new Class[] { HelloWebSecurityConfiguration. class };
}
...
}

Spring Security通常在web.xml中包含下面几行代码进行初始化:

1
2
3
4
5
6
7
8
9
10
11
12
<!-- Creates the Spring Container shared by all Servlets and Filters -->
< listener >
   < listener-class >
     org.springframework.web.context.ContextLoaderListener
   </ listener-class >
</ listener >
 
<!-- Load all Spring XML configuration including our security.xml file -->
< context-param >
   < param-name >contextConfigLocation</ param-name >
   < param-value >/WEB-INF/spring/*.xml</ param-value >
</ context-param >

AbstractSecurity WebApplicationInitializer

最后一步,我们需要对springSecurityFilterChain定义映射路径。我们很容易通过继承AbstractSecurityWebApplicationInitializer实现,并可以有选择的通过覆盖方法来定制映射。

下面是最基本的配置,它可以接受默认的映射路径,springSecurityFilterChain具有以下的特性:

  • springSecurityFilterChain映射到了”/*”
  • springSecurityFilterChain使用ERROR和REQUEST分派类型(dispatch type)
  • springSecurityFilterChain插入到其它已经配置的servlet过滤器映射(servlet Filter mapping)之前
1
2
3
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
}

上面的代码等同于将这几行代码放在web.xml中:

1
2
3
4
5
6
7
8
9
10
11
12
13
< filter >
   < filter-name >springSecurityFilterChain</ filter-name >
   < filter-class >
     org.springframework.web.filter.DelegatingFilterProxy
   </ filter-class >
</ filter >
 
< filter-mapping >
   < filter-name >springSecurityFilterChain</ filter-name >
   < url-pattern >/*</ url-pattern >
   < dispatcher >ERROR</ dispatcher >
   < dispatcher >REQUEST</ dispatcher >
</ filter-mapping >

WebApplicationInitializer的次序
在AbstractSecurityWebApplicationInitializer启动之后再加入的servlet过滤器映射,它们有可能会加在springSecurityFilterChain之前。除非这个应用不需要安全验证,否则springSecurityFilterChain需要放在其它所有的过滤器映射之前。@Order可以保证任何WebApplicationInitializer都使用特定的顺序加载。

CustomWebSecurityConfigurerAdapter

这个HelloWebSecurityConfiguration范例,为我们很好的展示了Spring Security Java配置是如何工作的。让我们来看看更多定制的配置吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@EnableWebSecurity
@Configuration
public class CustomWebSecurityConfigurerAdapter extends
WebSecurityConfigurerAdapter {
@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) {
auth
.inMemoryAuthentication()
.withUser( "user" ) // #1
.password( "password" )
.roles( "USER" )
.and()
.withUser( "admin" ) // #2
.password( "password" )
.roles( "ADMIN" , "USER" );
}
 
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers( "/resources/**" ); // #3
}
 
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeUrls()
.antMatchers( "/signup" , "/about" ).permitAll() // #4
.antMatchers( "/admin/**" ).hasRole( "ADMIN" ) // #6
.anyRequest().authenticated() // #7
.and()
.formLogin() // #8
.loginUrl( "/login" ) // #9
.permitAll(); // #5
}
}

我们也需要更新AbstractAnnotationConfigDispatcherServletInitializer,这样CustomWebSecurityConfigurerAdapter可以实现以下功能:

  • #1 可以在内存中的验证(memory authentication)叫作”user”的用户
  • #2 可以在内存中的验证(memory authentication)叫作”admin”的管理员用户
  • #3 忽略任何以”/resources/”开头的请求,这和在XML配置http@security=none的效果一样
  • #4 任何人(包括没有经过验证的)都可以访问”/signup”和”/about”
  • #5 任何人(包括没有经过验证的)都可以访问”/login”和”/login?error”。permitAll()是指用户可以访问formLogin()相关的任何URL。
  • #6 “/admin/”开头的URL必须要是管理员用户,譬如”admin”用户
  • #7 所有其他的URL都需要用户进行验证
  • #8 使用Java配置默认值设置了基于表单的验证。使用POST提交到”/login”时,需要用”username”和”password”进行验证。
  • #9 注明了登陆页面,意味着用GET访问”/login”时,显示登陆页面

下面的XML配置和上面的Java配置类似:

Java配置和XML命名空间的相同之处

在看过了更复杂的例子之后,你可能已经找到了一些XML命名空间和Java配置的相似之处。我在这里说明几条有用的信息:

  • HttpSecurity和http命名空间类似。它可以对于某一部分请求进行特别配置。要看个完整的配置实例,详见SampleMultiHttpSecurityConfig
  • WebSecurity和Security的命名空间的元素很类似,后者是针对web的,不需要父节点(security=none, debug等等)。可以对整个web security进行配置。
  • WebSecurityConfigurerAdapter方便我们定制WebSecurity和HttpSecurity。我们可以对WebSecurityConfigurerAdapter进行多次继承,以实现不同的http行为。详细的实例参见SampleMultiHttpSecurityConfig
  • 我们以上的Java配置代码作了代码格式化,所以易于阅读。“and()”类似于XML中结束一个元素的结束符。

Java配置和XML命名空间的不同之处

你已经意识到了XML和Java配置的不同之处

  • 当你在”#1″和“#2”中创建用户的时候,我们并没有设置为”ROLE_“前缀,而我们在XML设置成了“ROLE_USER”。因为这是个管理,”roles()”方法会自动添加”ROLE_“。如果你不想要”ROLE_“,你可以使用”authoritites()”方法。
  • Java配置有一些不同的默认URL和参数。当要创建自定义的登陆页面的时候要将这一条牢记在心。默认的URL使我们的URL更加RESTful。另外,使用Spring Security可以帮我避免信息泄露)。例如:
    • GET访问/login登陆页面,而不是访问/spring_security_login
    • POST访问/login,而不是/j_spring_security_check
    • 用户名默认为parameter,而不是j_username
    • 密码默认是password,而不是j_password
  • Java配置可以更容易将多个请求映射到同样的角色上。#4就将两个URL作了映射,以便所有人都可以访问
  • Java移除了多余的代码。例如,在XML中我们不得不在form-login和intercept-url中重复两次”/login”,而在Java配置中,我们靠#5就轻易做到了让用户都能访问到和formLogin()相关的URL。
  • #6映射HTTP请求的时候,我们使用了“hasRole()”方法,我们也没有添加”ROLE_”前缀,而在XML中我们则添加了。这也是我们应该知道的惯例:”hasRole()”会自动添加”ROLE_”前缀。如果你不想要“ROLE_”前缀,你可以使用”access()”方法。

更多的示例

我们还提供了更多的示例,你应该想跃跃欲试了吧:

从XML命名空间到Java配置

如果你觉得从XML转变成Java配置有一定困难,你可以先看看这些测试。这些测试中,XML元素的名称以”Namespace”开头,中间是XML元素的名称,然后以”Tests”结尾。例如,你想学习如何将http元素转换成Java配置,你可以看看NamespaceHttpTests;你如果想学习如何将remember-me命名空间转换成Java配置,参见NamespaceRememberMeTests

欢迎反馈

如果你发现了bug,或者觉得有什么地方值得改进,请你不要犹豫,给我们留言!我们希望听到你的想法,以便在大部分人获得代码之前,我们便确保代码的正确性。很早的尝试新功能是一种简单有效的回馈社区的方法,这样做的好处就是能帮助你获得你希望获得的功能。

请到“Java Config”目录下的Spring Security JIRA记录下任何问题。记录了一个JIRA之后,我们希望(当然并不是必须的)你在pull request中提交你的代码。你可以在贡献者指引中阅读更详细的步骤。如果你有任何不清楚的,请使用Spring Security论坛或者Stack Overflow,并使用”spring-security”标签(我会一直查看这个标签)。如果你针对这个博客有任何意见,也请留言。使用合适的工具对每个人来说都会带来便利。

结论

你可能已经对基于web的security的Java配置已经有了一定的认识了。下一篇中,我们将会带你来看下如何用Java配置来配置基于method的security。

原文链接:  Springsource  翻译:  ImportNew.com  -  唐小娟
译文链接:  http://www.importnew.com/5641.html
[  转载请保留原文出处、译者和译文链接。 ]
Spring Security权限控制系列 过滤器链中的每一个过滤器都是有系统提供的,每种过滤器都处理不同方面的事,如果我们希望在现有的过滤器链中加入我们的一些处理过滤该如何操作?Spring Security为我们提供了往过滤器链中添加过滤器的接口,接下来通过实例来看如何向过滤器链中添加我们自定义的过滤器,以此实现我们自己的逻辑。自定义过滤器@Component= null) {}}}添加到过滤器链。... 阅读详情

相关推荐

SpringSecurity - 启动流程分析(一)

SpringSecurity 流程分析

业精于勤荒于嬉 1590

Spring Security 六 WebSecurityConfigurerAdapter

文章目录一、WebSecurityConfigurerAdapter是什么?1.WebSecurityConfigurer是什么?2.WebSecurity2.1 WebSecurity定义2.2 AbstractConfiguredSecurityBuilder2.3二、使用步骤1.引入库2.读入数据总结 一、WebSecurityConfigurerAdapter是什么? WebSecurityConfigurerAdapter是为创建WebSecurityConfigurer实例提供方便的基类,该类允

weixin_43172297的博客 8580

没有WebSecurityConfigurerAdapter的Spring Security

在Spring Security 5.7.0-M2中,我们弃用了WebSecurityConfigurerAdapter,因为我们鼓励用户转向基于组件的安全配置。

Kwoky的博客 4948

WebSecurityConfigurerAdapter过时的替代方式

SpringSecurity配置,用着用着就过期了,而且还报unsafe异常,真的是不让懒人活着啊。

随风飘絮 6432

SpringBoot - WebSecurityConfigurerAdapter的作用是什么?

Spring Security提供了一个抽象类WebSecurityConfigurerAdapter,它实现了默认的认证和授权,允许用户自定义一个WebSecurity类,重写其中的三个configure来实现自定义的认证和授权。

记录并分享 6633

泛微Ecology9接口调用全流程:从配置到实战Java代码解析

本文详细解析了泛微Ecology9系统接口的完整调用流程,涵盖安全架构、服务端配置与客户端Java实战代码。重点阐述了基于RSA加密的认证机制、Token管理策略,并提供了企业级集成的核心代码示例与生产环境调优建议,帮助开发者安全、高效地实现系统对接。

m9n0o的博客 836

WebSecurityConfigurerAdapter已弃用

在 Spring Security 5.7.0-M2 中,弃用了 `WebSecurityConfigurerAdapter`,Spring 鼓励用户转向基于组件的安全配置。

lazy_LYF的博客 3万+

ADC选型实战:从参数指标到精准应用的工程指南

本文深入解析ADC(模数转换器)选型的关键参数与实战技巧,涵盖分辨率、转换误差等核心指标,并提供高精度温度测量、高速数据采集等五大应用场景的选型指南。通过实际案例和代码示例,详细讲解校准方法、功耗优化策略及常见问题排查,帮助工程师实现从参数指标到精准应用的工程实践。

weixin_29166013的博客 326

深入理解 WebSecurityConfigurerAdapter【源码篇】

我们继续来撸 Spring Security 源码,今天来撸一个非常重要的 WebSecurityConfigurerAdapter。 我们的自定义都是继承自 WebSecurityConfigurerAdapter 来实现的,但是对于 WebSecurityConfigurerAdapter 内部的工作原理,配置原理,很多小伙伴可能都还不太熟悉,因此我们今天就来捋一捋。 我们先来看一张 WebSecurityConfigurerAdapter 的继承关系图: 在这层继承关系中,有两个非常重要的类: S

江南一点雨的专栏 1万+

不只是抓取:用五指灵巧手(ROH-A001/RH56)玩转ROS2下的力控与混合控制

本文深入探讨了在ROS2环境下使用五指灵巧手(ROH-A001/RH56)实现力控与混合控制的实战技巧。从硬件通信协议解析到ROS2节点开发,详细介绍了力感知架构、实时数据处理和混合控制策略,帮助开发者在Ubuntu系统中高效实现精密操作。通过鸡蛋抓取等实例,展示了力控技术在机器人灵巧操作中的关键作用。

weixin_28221501的博客 285

STC8H DMA 串口1全双工中断方式收发通讯C语言

串口1全双工中断方式收发通讯程序。 通过PC向MCU发送数据, MCU将收到的数据自动存入DMA空间. 当DMA空间存满设置大小的内容后,通过串口1的DMA自动发送功能把存储空间的数据原样返回. 用定时器做波特率发生器,建议使用1T模式(除非低波特率用12T),并选择可被波特率整除的时钟频率,以提高精度。

czhaii的专栏 1466

SpringSecurity WebSecurityConfigurerAdapter类使用

WebSecurityConfigurerAdapter 类是个适配器, 在配置的时候,需要我们自己写个配置类去继承他,然后编写自己所特殊需要的配置 @Configuration @EnableWebSecurity public class WebSecurityConfigextends WebSecurityConfigurerAdapter { @Override pro...

weixin_42849689的博客 7万+

YOLOv8自定义训练:车牌识别全流程(从标注到推理,附可视化代码)

车牌检测全流程实践指南 摘要:本文详细介绍了基于YOLOv8的车牌检测完整实现方案。针对车牌检测中的三大难点(小目标、多角度、光照变化),提供了从数据准备到模型部署的全流程解决方案。重点包括:1)数据采集与标注规范;2)针对小目标的YOLOv8模型优化配置;3)K-means锚框聚类方法;4)训练参数调优策略。通过实际验证,该方法可获得95%以上的检测准确率,并附有完整的代码实现和可视化工具,便于开发者快速复现应用。 (字数:149字)

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

【Spring Security】—— WebSecurityConfigurerAdapter

官网地址 Spring Security Reference 版本:Version 5.5.0 WebSecurityConfigurerAdapter 继承关系图 Adapter 谷歌翻译:n. 【机】转接器 【网络】 适配器;适配器模式;接头。通过类名了解功能:我的理解,这个类是一个Web应用安全配置“接头”,及用户可通过这个“接头”接到自己的配置,也就是用户可以利用这个类来定制化安全配置。 SecurityBuilder 接口 对这个接口暂时没有细看,先根据官网了解了一下这个接口想要实

qq_33471737的博客 4430

Unity最强动作战斗框架?Combat System Framework 深度解析

Combat System Framework 并不是一个简单的角色控制器,而是一套完整的动作游戏战斗开发框架。它借鉴了现代 AAA 游戏常见的架构思想,以 Gameplay Tag 为核心,结合 ScriptableObject 数据驱动设计,将技能、属性、Buff、伤害、武器、动画通知等系统有机整合在一起。同时,配套的可视化动画时间轴、Root Motion 工具和实时预览窗口,大幅优化了动作开发流程。当然,这套框架也有一定的学习门槛。

2403_88403568的博客 679

【Windows Server 2019】DNS服务器的配置与管理——DNS正向解析

博文介绍了如何使用正向解析区,包括创建和添加并验证,以及术语 主机记录,别名,邮件交换记录的解释。

VMware, Windows, Linux, Cisco, Container, Kubernetes, Kali 1万+

Spring Security 替换WebSecurityConfigurerAdapter (Deprecated)的方法

在本文中,我将提供一个解决方案来配置Spring 安全性,而无需 WebSecurityConfigurerAdapter 类。在上面的例子中,我们遵循最佳实践,使用 Spring Security lambda DSL 和方法。我们创建了一个Spring Java配置类,它扩展了。类进行 Spring 安全配置,稍后我们将看到如何将此安全配置迁移到基于组件的方法。类的 JWT 配置,稍后我们将看到如何将此安全配置迁移到基于组件的方法。类已被弃用,Spring 团队鼓励用户转向基于组件的安全配置。

allway2的博客 2万+

K8S搭建(centos)四、安装K8S

每个人都有惰性,但不断学习是好好生活的根本,共勉!

感谢阅读 2644

SpringSecurity - WebSecurityConfigurerAdapter 过时问题

WebSecurityConfigurerAdapter 过时问题

业精于勤荒于嬉 1万+

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

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

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

WebSecurityConfigurerAdapter和ResourceServerConfigurerAdapter区别

默认继承了WebSecurityConfigurerAdapter之后,再加上几行代码,我们就能实现以下的功能: 1、要求用户在进入你的应用的任何URL之前都进行验证 2、创建一个用户名是“user”,密码是“password”,角色是“ROLE_USER”的用户 3、启用HTTP Basic和基于表单的验证 4、Spring Security将会自动生成一个登陆页面和登出成功页面 这样他就提...

门心叼龙的专栏 8519

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

Spring Security 5.7.0弃用 WebSecurityConfigurerAdapter

从Spring Security 5.7.0版本开始弃用 WebSecurityConfigurerAdapter 类,本篇文章参考Spring 博客文章介绍了如何在 5.7.0 版本之后正确使用Spring Security授权和认证等方式。

OLinOne的博客 1万+

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

19、关于WebSecurityConfigurerAdapter和ResourceServerConfigurerAdapter区别联系

一、区别与联系 1、ResourceServerConfigurerAdapter被配置为不同的端点(参见antMatchers),而WebSecurityConfigurerAdapter不是。 这两个适配器之间的区别在于,RealServServer配置适配器使用一个特殊的过滤器来检查请求中的承载令牌,以便通过OAuth2对请求进行认证。WebSecurityConfigurerAd...

lixiang987654321的专栏 1万+

websecurityconfigureradapter_深入理解 WebSecurityConfigurerAdapter「源码篇」

我们继续来撸 Spring Security 源码,今天来撸一个非常重要的 WebSecurityConfigurerAdapter。我们的自定义都是继承自 WebSecurityConfigurerAdapter 来实现的,但是对于 WebSecurityConfigurerAdapter 内部的工作原理,配置原理,很多小伙伴可能都还不太熟悉,因此我们今天就来捋一捋。我们先来看一张 WebSec...

weixin_39924584的博客 680
上一篇: IDEA+gradle +SpringBoot 项目,bootrun 无法启动项目
下一篇: Spring Boot中的注解
雨冰
博客等级 码龄15年 18粉丝 60原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值