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

Spring Security OAuth2.0认证授权 --- 基础篇 一、基本概念 1.1、什么是认证 进入移动互联网时代,大家每天都在刷手机,常用的软件有微信、支付宝、头条等,下边拿微信来举例子说明认证相关的基本概念,在初次使用微信前需要注册成为微信用户,然后输入账号和密码即可登录微信,输入账号和密码登录微信的过程就是认证。 系统为什么要认证? 认证是为了保护系统的隐私数据与资源,用户的身份合法方可访问该系统的资源。 认证 :用户认证就是判断一个用户的身份是否合法的过程,用户去访问系统资源时系统要求验证用户的身份信息,身份合法方可继续访问,不合法则拒绝访问。常见的用户身份认 阅读详情

前言

今天来聊聊一个接口对接的场景,A厂家有一套HTTP接口需要提供给B厂家使用,由于是外网环境,所以需要有一套安全机制保障,这个时候oauth2就可以作为一个方案。

关于oauth2,其实是一个规范,本文重点讲解spring对他进行的实现,如果你还不清楚授权服务器,资源服务器,认证授权等基础概念,可以移步理解OAuth 2.0 - 阮一峰,这是一篇对于oauth2很好的科普文章。

需要对spring security有一定的配置使用经验,用户认证这一块,spring security oauth2建立在spring security的基础之上。第一篇文章主要是讲解使用springboot搭建一个简易的授权,资源服务器,在文末会给出具体代码的github地址。后续文章会进行spring security oauth2的相关源码分析。java中的安全框架如shrio,已经有跟我学shiro - 开涛,非常成体系地,深入浅出地讲解了apache的这个开源安全框架,但是spring security包括oauth2一直没有成体系的文章,学习它们大多依赖于较少的官方文档,理解一下基本的使用配置;通过零散的博客,了解一下他人的使用经验;打断点,分析内部的工作流程;看源码中的接口设计,以及注释,了解设计者的用意。spring的各个框架都运用了很多的设计模式,在学习源码的过程中,也大概了解了一些套路。spring也在必要的地方添加了适当的注释,避免了源码阅读者对于一些细节设计的理解产生偏差,让我更加感叹,spring不仅仅是一个工具框架,更像是一个艺术品。


作者:老徐

原文地址:http://t.cn/Rp7xUro

友情提示:欢迎关注公众号【芋道源码】。????关注后,拉你进【源码圈】微信群和【老徐】搞基嗨皮。

友情提示:欢迎关注公众号【芋道源码】。????关注后,拉你进【源码圈】微信群和【老徐】搞基嗨皮。

友情提示:欢迎关注公众号【芋道源码】。????关注后,拉你进【源码圈】微信群和【老徐】搞基嗨皮。

概述

使用oauth2保护你的应用,可以分为简易的分为三个步骤

  • 配置资源服务器

  • 配置认证服务器

  • 配置spring security

前两点是oauth2的主体内容,但前面我已经描述过了,spring security oauth2是建立在spring security基础之上的,所以有一些体系是公用的。

oauth2根据使用场景不同,分成了4种模式

  • 授权码模式(authorization code)

  • 简化模式(implicit)

  • 密码模式(resource owner password credentials)

  • 客户端模式(client credentials)

本文重点讲解接口对接中常使用的密码模式(以下简称password模式)和客户端模式(以下简称client模式)。授权码模式使用到了回调地址,是最为复杂的方式,通常网站中经常出现的微博,qq第三方登录,都会采用这个形式。简化模式不常用。

项目准备

主要的maven依赖如下

<!-- 注意是starter,自动配置 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 不是starter,手动配置 -->
<dependency>
   <groupId>org.springframework.security.oauth</groupId>
   <artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 将token存储在redis中 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

我们给自己先定个目标,要干什么事?既然说到保护应用,那必须得先有一些资源,我们创建一个endpoint作为提供给外部的接口:

@RestController
public class TestEndpoints {

   @GetMapping("/product/{id}")
   public String getProduct(@PathVariable String id) {
       //for debug
       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       return "product id : " + id;
   }

   @GetMapping("/order/{id}")
   public String getOrder(@PathVariable String id) {
       //for debug
       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       return "order id : " + id;
   }

}

暴露一个商品查询接口,后续不做安全限制,一个订单查询接口,后续添加访问控制。

配置资源服务器和授权服务器

由于是两个oauth2的核心配置,我们放到一个配置类中。
为了方便下载代码直接运行,我这里将客户端信息放到了内存中,生产中可以配置到数据库中。token的存储一般选择使用redis,一是性能比较好,二是自动过期的机制,符合token的特性。

@Configuration
public class OAuth2ServerConfig {

   private static final String DEMO_RESOURCE_ID = "order";

   @Configuration
   @EnableResourceServer
   protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

       @Override
       public void configure(ResourceServerSecurityConfigurer resources) {
           resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
       }

       @Override
       public void configure(HttpSecurity http) throws Exception {
           // @formatter:off
           http
                   // Since we want the protected resources to be accessible in the UI as well we need
                   // session creation to be allowed (it's disabled by default in 2.0.6)
                   .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                   .and()
                   .requestMatchers().anyRequest()
                   .and()
                   .anonymous()
                   .and()
                   .authorizeRequests()
//                    .antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')")
                   .antMatchers("/order/**").authenticated();//配置order访问控制,必须认证过后才可以访问
           // @formatter:on
       }
   }

   @Configuration
   @EnableAuthorizationServer
   protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

       @Autowired
       AuthenticationManager authenticationManager;
       @Autowired
       RedisConnectionFactory redisConnectionFactory;

       @Override
       public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
           //配置两个客户端,一个用于password认证一个用于client认证
           clients.inMemory().withClient("client_1")
                   .resourceIds(DEMO_RESOURCE_ID)
                   .authorizedGrantTypes("client_credentials", "refresh_token")
                   .scopes("select")
                   .authorities("client")
                   .secret("123456")
                   .and().withClient("client_2")
                   .resourceIds(DEMO_RESOURCE_ID)
                   .authorizedGrantTypes("password", "refresh_token")
                   .scopes("select")
                   .authorities("client")
                   .secret("123456");
       }

       @Override
       public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
           endpoints
                   .tokenStore(new RedisTokenStore(redisConnectionFactory))
                   .authenticationManager(authenticationManager);
       }

       @Override
       public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
           //允许表单认证
           oauthServer.allowFormAuthenticationForClients();
       }

   }

}

简单说下spring security oauth2的认证思路。

  • client模式,没有用户的概念,直接与认证服务器交互,用配置中的客户端信息去申请accessToken,客户端有自己的clientid,clientsecret对应于用户的username,password,而客户端也拥有自己的authorities,当采取client模式认证时,对应的权限也就是客户端自己的authorities。

  • password模式,自己本身有一套用户体系,在认证时需要带上自己的用户名和密码,以及客户端的clientid,clientsecret。此时,accessToken所包含的权限是用户本身的权限,而不是客户端的权限。

我对于两种模式的理解便是,如果你的系统已经有了一套用户体系,每个用户也有了一定的权限,可以采用password模式;如果仅仅是接口的对接,不考虑用户,则可以使用client模式。

配置spring security

在spring security的版本迭代中,产生了多种配置方式,建造者模式,适配器模式等等设计模式的使用,spring security内部的认证flow也是错综复杂,在我一开始学习ss也产生了不少困惑,总结了一下配置经验:使用了springboot之后,spring security其实是有不少自动配置的,我们可以仅仅修改自己需要的那一部分,并且遵循一个原则,直接覆盖最需要的那一部分。这一说法比较抽象,举个例子。比如配置内存中的用户认证器。有两种配置方式

planA:

@Bean
protected UserDetailsService userDetailsService(){
   InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
   manager.createUser(User.withUsername("user_1").password("123456").authorities("USER").build());
   manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build());
   return manager;
}

planB:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.inMemoryAuthentication()
               .withUser("user_1").password("123456").authorities("USER")
               .and()
               .withUser("user_2").password("123456").authorities("USER");
  }

  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
      AuthenticationManager manager = super.authenticationManagerBean();
       return manager;
   }
}

你最终都能得到配置在内存中的两个用户,前者是直接替换掉了容器中的UserDetailsService,这么做比较直观;后者是替换了AuthenticationManager,当然你还会在SecurityConfiguration 复写其他配置,这么配置最终会由一个委托者去认证。如果你熟悉spring security,会知道AuthenticationManager和AuthenticationProvider以及UserDetailsService的关系,他们都是顶级的接口,实现类之间错综复杂的聚合关系...配置方式千差万别,但理解清楚认证流程,知道各个实现类对应的职责才是掌握spring security的关键。

下面给出我最终的配置:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

   @Bean
   @Override
   protected UserDetailsService userDetailsService(){
       InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
       manager.createUser(User.withUsername("user_1").password("123456").authorities("USER").build());
       manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build());
       return manager;
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       // @formatter:off
       http
           .requestMatchers().anyRequest()
           .and()
               .authorizeRequests()
               .antMatchers("/oauth/*").permitAll();
       // @formatter:on
   }
}

重点就是配置了一个UserDetailsService,和ClientDetailsService一样,为了方便运行,使用内存中的用户,实际项目中,一般使用的是数据库保存用户,具体的实现类可以使用JdbcDaoImpl或者JdbcUserDetailsManager。

获取token

进行如上配置之后,启动springboot应用就可以发现多了一些自动创建的endpoints:

{[/oauth/authorize]}
{[/oauth/authorize],methods=[POST]
{[/oauth/token],methods=[GET]}
{[/oauth/token],methods=[POST]}
{[/oauth/check_token]}
{[/oauth/error]}

重点关注一下/oauth/token,它是获取的token的endpoint。启动springboot应用之后,使用http工具访问
password模式:

http://localhost:8080/oauth/token?username=user_1&password=123456&grant_type=password&scope=select&client_id=client_2&client_secret=123456

响应如下:
{"access_token":"950a7cc9-5a8a-42c9-a693-40e817b1a4b0","token_type":"bearer","refresh_token":"773a0fcd-6023-45f8-8848-e141296cb3cb","expires_in":27036,"scope":"select"}

client模式:
http://localhost:8080/oauth/token?grant_type=client_credentials&scope=select&client_id=client_1&client_secret=123456

响应如下:
{"access_token":"56465b41-429d-436c-ad8d-613d476ff322","token_type":"bearer","expires_in":25074,"scope":"select"}

在配置中,我们已经配置了对order资源的保护,如果直接访问:http://localhost:8080/order/1会得到这样的响应:{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}
(这样的错误响应可以通过重写配置来修改)

而对于未受保护的product资源http://localhost:8080/product/1则可以直接访问,得到响应product id : 1

携带accessToken参数访问受保护的资源:

使用password模式获得的token:http://localhost:8080/order/1?access_token=950a7cc9-5a8a-42c9-a693-40e817b1a4b0,得到了之前匿名访问无法获取的资源:order id : 1

使用client模式获得的token:http://localhost:8080/order/1?access_token=56465b41-429d-436c-ad8d-613d476ff322,同上的响应order id : 1

我们重点关注一下debug后,对资源访问时系统记录的用户认证信息,可以看到如下的debug信息

password模式:

client模式:

和我们的配置是一致的,仔细看可以发现两者的身份有些许的不同。想要查看更多的debug信息,可以选择下载demo代码自己查看,为了方便读者调试和验证,我去除了很多复杂的特性,基本实现了一个最简配置,涉及到数据库的地方也尽量配置到了内存中,这点记住在实际使用时一定要修改。

到这儿,一个简单的oauth2入门示例就完成了,一个简单的配置教程。token的工作原理是什么,它包含了哪些信息?spring内部如何对身份信息进行验证?以及上述的配置到底影响了什么?这些内容会放到后面的文章中去分析。

示例代码下载

全部的代码可以在我的github上进行下载,项目使用springboot+maven构建:
https://github.com/lexburner/oauth2-demo

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

相关推荐

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

上一篇文章中我们介绍了获取token的流程,这一篇重点分析一下,携带token访问受限资源时,内部的工作流程。@EnableResourceServer与@EnableAuthorizationServer还记得我们在第一节中就介绍过了OAuth2的两个核心概念,资源服务器与身份认证服务器。我们对两个注解进行配置的同时,到底触发了内部的什么相关配置呢?上一篇文章重点介绍的其实是与身份认证相关的流程,

徐靖峰的专栏 6万+

spring Security4 和 oauth2整合 注解+xml混合使用(基础运行篇)

Spring Security4 和 oauth2整合最近项目中需要用到oauth2,到网上找了好多资料,全是乱七八糟的,东拼西凑,终于跑出来了一版,xml的方式太乱了,跑不了,还是用注解方式,并把一些关键配置提到xml中。git地址:https://gitee.com/xiaoyaofeiyang/OauthUmpspring Security4 和 oauth2整合 注解+xml混合使用

feiyangtianyao的专栏 3945

整合spring+pring mvc+mybatis

整合spring+pring mvc+mybatis,数据库是Oracle,完整demo, 访问地址: http://127.0.0.1:8080/bigdt/user/listUser.do

OAuth2学习笔记

目前很多开放平台如新浪微博开放平台都在使用提供开放API接口供开发者使用,随之带来了第三方应用要到开放平台进行授权的问题,OAuth就是干这个的,OAuth2是OAu...

一个有趣、有料、有内涵的地方! 460

PCB压合原理与工艺全流程深度解析

PCB压合是多层印制电路板制造中的核心工序,其本质并非简单物理叠加,而是高分子树脂流动、玻璃布应力释放、铜箔热膨胀及界面能调控的协同过程。理解压合原理,需掌握温度-压力-时间三维曲线动态关系;优化工艺流程,须兼顾叠板精度、热压参数匹配与冷却策略;关键影响因素如半固化片(PP)选型、铜箔表面处理、设备温场均匀性、结构对称性、环境湿度及操作手法,共同决定层间结合力、翘曲度与孔壁质量。本文围绕PCB压合原理、工艺流程、关键影响因素三大维度展开,融合IPC标准、实测数据与产线案例,为工艺工程师、NPI人员及设备维护

weixin_29191081的博客 260

硬件工程师八大细分岗位详解:从芯片到整机的技术分工与职业选择

硬件工程作为电子系统设计的核心领域,涉及从芯片级到整机级的完整技术链条。其基本原理是通过电路设计、信号处理和功率管理等技术,将电子元件集成为功能完备的硬件系统。随着产品复杂度提升,硬件工程师岗位出现高度专业化分工,这种细分不仅提升了技术深度,更优化了团队协作效率。在工程实践中,信号完整性和电源完整性成为高速数字设计的两个关键技术挑战,直接影响系统稳定性。本文基于行业热词"硬件工程师"和"信号完整性",深入解析八大细分岗位的技术差异,帮助从业者明确职业发展方向,构建系统化的硬件设计思维。

weixin_33811539的博客 458

SpringSecruity整合Oauth2 详解(一)

文章目录一、创建项目添加依赖二、添加application.properties三、配置授权服务器四、配置资源服务器五、配置Spring Security五、测试验证 前言:上一章Oauth2 详解介绍了Oauth2是干什么的,使用场景,和运行原理以及授权模式。 这一章我们主要以密码模式举例 密码模式: 第一步:用户访问用页面时,输入第三方认证所需要的信息(QQ/微信账号密码) 第二步:应用页面...

境里婆娑 1319

SystemRDL:从寄存器描述到自动化生成的完整指南

本文详细介绍了SystemRDL如何通过“一份描述,多处生成”的理念,彻底解决芯片与FPGA设计中手动维护寄存器带来的不一致与低效问题。文章提供了从语言快速上手、核心组件讲解到使用PeakRDL工具链实现自动化代码与文档生成的完整实战指南,帮助硬件工程师构建高效、可靠的寄存器开发流程。

weixin_29243279的博客 664

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

本文开始从源码的层面,讲解一些Spring Security Oauth2的认证流程。本文较长,适合在空余时间段观看。且涉及了较多的源码,非关键性代码以…代替。获取token上一篇博客中我们尝试使用了password模式和client模式,有一个比较关键的endpoint:/oauth/token。从这个入口开始分析,spring security oauth2内部是如何生成token的。首先开启d

徐靖峰的专栏 3万+

Ribo测序翻译效率计算及可视化

本文介绍了一个计算翻译效率(TE)和分析转录-翻译相关性的生物信息学流程。首先通过Python脚本从标准化表达量矩阵(TPM/FPKM)计算TE值,该脚本自动匹配转录组(RNA)和翻译组(Ribo)样本进行比值运算。然后使用R语言进行相关性分析,通过ggplot2绘制样本间转录-翻译表达量的散点图,添加线性回归线和相关系数标注,支持PNG/PDF格式输出。整个流程实现了从原始数据处理到可视化分析的全过程。

Tiaoxiaobai的博客 557

AI 大模型应用数据中心的数据清洗工具

1. 背景介绍 在人工智能大模型应用的浪潮中,数据清洗作为数据预处理的重要环节,对于提升模型性能和可靠性具有至关重要的作用。数据中心作为人工智能模型的运行环境,面临着海量数据流和多样化的数据类型,如何高效、准确地进行数据清洗,成为应用大模型的关键问题之一。本文将详细介绍AI大模型应用数据中心的数据清洗工具,包括核心概念、算法原理、具体操作步骤、应用场

SuperAGI2025 1806

Spring Security OAuth2 入门

1. 概述 2. 引入 Spring Security OAuth2 依赖 3. 配置资源服务器 4. 配置授权服务器 4.1 授权码模式 Spring Security Setting 4.2 密码模式 4.3 简化模式 4.4 客户端模式 4.5 如何选择? 4.6 为什么有 Client 编号和密码 5. 刷新令牌 5.1 获取刷新令牌 5.2 “刷新”访问令牌 5.3 为什么需要有刷新令牌 6. 删除令牌 6.1 删除访问令牌 6.2 删除刷新令牌 6.3 RFC

m0_62714732的博客 9860

大模型部署指南:SGLang 框架

本文介绍使用 SGLang 框架部署大模型

举世誉之而不加劝,举世非之而不加沮,定乎内外之分,辩乎荣辱之境,斯已矣。 1620

spring security oauth2 教程

理解OAuth 2.0 http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html OAuth 2.0基本概念和运作流程 https://segmentfault.com/a/1190000013467122 架构图 验证流程 spring security oauth2源码架构图 绿色的代表实体类,蓝色的代表接口方法 ...

tom和cat的博客 5294

【异常】XXL-JOB提示异常ERROR com.xxl.job.core.util.XxlJobRemotingUtil - connect timed out

打开XXL-JOB的ELK,发现一堆报错。

奶爸的编程之路,也就一周冷个三天 2049

【OAG vs RAG】OAG工程实战(下):权限治理与多模型协同

本文摘要(149字): OAG工程体系的核心挑战在于权限治理与多模型协同。文章深入探讨OMA(对象管理权限)系统,实现细粒度访问控制:通过对象级权限管理行级安全,属性级权限控制敏感字段脱敏,确保AI Agent权限不越界。系统采用三层次防护:对象策略控制记录可见性,属性策略处理字段级脱敏,动作策略限制操作范围。权限验证贯穿Agent执行全流程,结合多模型交叉验证机制,构建企业级AI安全防线。这些设计使OAG系统从技术演示升级为生产可用的企业解决方案。

求知若渴、虚心若愚 105

Spring Security OAuth2 实现登录互踢

背景说明 一个账号只能一处登录,类似的业务需求在现有后管类系统是非常常见的。 但在原有的 spring security oauth2 令牌方法流程(所谓的登录)无法满足类似的需求。 我们先来看 TokenEndpoint 的方法流程 客户端 带参访问 /oauth/token 接口,最后去调用 TokenGranter TokenGranter 根据不同的授权类型,获取用户认证信息 并去调用...

冷冷的博客 7810

深度学习工具包 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-oauth2的token创建原理

1.org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer 此类默认配置了创建access_token需要用到的一些组件, 比如:AuthorizationServerTokenServices(默认为DefaultTokenSe...

2651

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Spring Security 实战干货:OAuth2登录获取Token的核心逻辑

1. 前言在上一篇Spring Security 实战干货:OAuth2 授权回调的核心认证流程中,我们讲了当第三方同意授权后会调用redirectUri发送回执给我们的服务器。我们的服务...

码农小胖哥 3968

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

上一篇: 【死磕Java并发】—– J.U.C之重入锁:ReentrantLock
下一篇: Dubbo源码解析 —— Zookeeper 订阅
公众号-芋道源码
博客等级 码龄10年 1639粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值