学习笔记:微服务-9 spring cloud oauth2 server配置

Spring Cloud下基于OAUTH2认证授权的实现 阅读详情

spring cloud 对外服务的统一认证,以及各微服务之间相互调用的身份认证,需要有个认证服务器,上两节学习了以cas中央认证服务器作认证,作为spring cloud全家桶,本身提供了oauth2的统一认证,能很好地集成在整个微服务集群中,这节就学习oauth2服务器的搭建

1. 新建spring boot start project 我这设置项目名为:MicroserviceOauth2Server8301

2. pom.xml 加入以下依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

3. application.properties 配置

server.port: 8301
spring.application.name=MicroserviceOauth2Server8301
spring.cloud.discovery.enabled=true
spring.redis.host= centos7.linbsoft.com
spring.redis.port=6379
eureka.client.serviceUrl.defaultZone=http://admin:123@centos7.linbsoft.com:8101/eureka/,http://admin:123@microservice1.linbsoft.com:8102/eureka/
logging.level.org.springframework.security=DEBUG

4. 启动类 MicroserviceOauth2Server8301Application

@EnableDiscoveryClient
@SpringBootApplication
public class MicroserviceOauth2Server8301Application {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceOauth2Server8301Application.class, args);
    }
}

5.  授权服务配置类AuthorizationServerConfig,这里的登录客户是写死在内存的,实际部署可以通过数据库读取。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;    // 认证管理器
  
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;  // redis连接工厂

    /**
     * 令牌存储
     * @return redis令牌存储对象
     */
    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }
   
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(this.authenticationManager);
        endpoints.tokenStore(tokenStore());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("admin")
                .scopes("read")
                .secret(new BCryptPasswordEncoder().encode("123456"))
                .authorizedGrantTypes("password", "authorization_code", "refresh_token")
                .and()
                .withClient("webapp")
                .scopes("xx")
                .authorizedGrantTypes("implicit");
    }

}

6. 应用服务器网站本身的安全配置类SecurityConfig

Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        return new CustomUserDetailsService();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // return PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
      //  auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
        auth.userDetailsService(userDetailsService());
    }

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


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and()
                .httpBasic().and().csrf().disable();
    }

7. oauth2本身也是一个资源服务器,配置类ResourceServerConfig

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new OAuth2RequestedMatcher())
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated();
    }


    private static class OAuth2RequestedMatcher implements RequestMatcher {
        @Override
        public boolean matches(HttpServletRequest request) {
            String auth = request.getHeader("Authorization");
            boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer");
            boolean haveAccessToken = request.getParameter("access_token")!=null;
            return haveOauth2Token || haveAccessToken;
        }
    }
   
}

8. 自定义用户服务类CustomUserDetailsService ,实例化方法  loadUserByUsername ,本方法的作用是根据登录用户名,查找获取用户类,包含用户账号,密码,权限等,这个一般需要查找数据库获取(与第5步的获取登录账号密码一致),这里demo就直接生成一个固定的用户测试。

@Service
public class CustomUserDetailsService implements UserDetailsService {
			
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		 System.out.println("当前的用户名是:"+username);
	        //这里为了方便测试,就直接返回一个用户信息,实际当中这里修改为查询数据库或者调用服务什么的来获取用户信息
           //根据登录名 到数据库取出用户信息
		 User user = mockUser();
			 return user;
	}		
	// BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
	private User mockUser() {
		Collection<GrantedAuthority> authorities = new HashSet<>();
		authorities.add(new SimpleGrantedAuthority("admin-role"));//用户所拥有的角色信息
		User user = new User("admin",new BCryptPasswordEncoder().encode("123456"),authorities);
	//	User user = new User("admin","12345",authorities);
		return user;
		}
}

9. 通过验证后,获取用户 map为 “/user”

@RestController
public class UserController {
@GetMapping("/user")
public Principal user(Principal user){
return user;
 }
}

10. 测试

首先可以通过Postman 测试api接口

以上是正常获取登录用户信息

也可以通过浏览器测试,输入账号密码后,即可看到保护的资源,这里是用户信息

 

测试流程:

1. 获取code

http://centos7.linbsoft.com:8301/oauth/authorize?response_type=code&client_id=admin&grant_type=code&redirect_uri=http://centos7.linbsoft.com:8301

弹出登录界面,登录后获取code

2. 获取token,post方法提交,把获取的code写入

http://centos7.linbsoft.com:8301/oauth/token?client_id=admin&grant_type=authorization_code&code=7hZ5jw&redirect_uri=http://centos7.linbsoft.com:8301

获取到token

{
    "access_token": "e86e7551-a01f-42af-830e-78f41c473bb8",
    "token_type": "bearer",
    "refresh_token": "647ddcaf-3416-47f7-8264-ebad1a374152",
    "expires_in": 42541,
    "scope": "read"
}

到redis查看到缓存的token

127.0.0.1:6379> keys *
 1) "uname_to_access:admin:admin"
 2) "auth:e86e7551-a01f-42af-830e-78f41c473bb8"
 3) "client_id_to_access:admin"
 4) "refresh:647ddcaf-3416-47f7-8264-ebad1a374152"
 5) "access:e86e7551-a01f-42af-830e-78f41c473bb8"
 6) "refresh_to_access:647ddcaf-3416-47f7-8264-ebad1a374152"
7) "refresh_auth:647ddcaf-3416-47f7-8264-ebad1a374152"
8) "access_to_refresh:e86e7551-a01f-42af-830e-78f41c473bb8"
9) "auth_to_access:35eb42947eaa87475ff2746ebe2a93f1"
 

3.用获取的token 访问资源

http://centos7.linbsoft.com:8301/user?access_token=e86e7551-a01f-42af-830e-78f41c473bb8

返回如下:

{"authorities":[{"authority":"admin-role"}],"details":{"remoteAddress":"192.168.49.141","sessionId":"724EE7828B6D43CD6D76C52101895155","tokenValue":"e86e7551-a01f-42af-830e-78f41c473bb8","tokenType":"Bearer","decodedDetails":null},"authenticated":true,"userAuthentication":{"authorities":[{"authority":"admin-role"}],"details":{"remoteAddress":"192.168.49.141","sessionId":null},"authenticated":true,"principal":{"password":null,"username":"admin","authorities":[{"authority":"admin-role"}],"accountNonExpired":true,"accountNonLocked":true,"credentialsNonExpired":true,"enabled":true},"credentials":null,"name":"admin"},"oauth2Request":{"clientId":"admin","scope":["read"],"requestParameters":{"code":"WgI15s","grant_type":"authorization_code","response_type":"code","redirect_uri":"http://centos7.linbsoft.com:8301","client_id":"admin"},"resourceIds":[],"authorities":[],"approved":true,"refresh":false,"redirectUri":"http://centos7.linbsoft.com:8301","responseTypes":["code"],"extensions":{},"grantType":"authorization_code","refreshTokenRequest":null},"principal":{"password":null,"username":"admin","authorities":[{"authority":"admin-role"}],"accountNonExpired":true,"accountNonLocked":true,"credentialsNonExpired":true,"enabled":true},"credentials":"","clientOnly":false,"name":"admin"}

本学习参考多位网友文章,在此不一一列出,谢谢。

 

 

Spring Cloud OAuth2(基于JWT)的微服务认证授权实战 文章目录1.简介1.1解决方案1.2案例工程架构2.构建auth-server工程2.1添加maven依赖2.2创建数据表2.3 添加配置2.4 自定义UserDetailsService2.5 认证授权配置2.6 扩展token增强器TokenEnhancer2.7 认证授权服务器配置2.8 认证授权服务器测试3.构建auth-client工程3.1 添加maven依赖3.2 重写token解析器3.3 解决Feign接口调用Token传递问题3.4 资源服务器配置4.构建资源服务器应用user-serv 阅读详情

相关推荐

微服务安全实战:基于Spring Cloud Alibaba与OAuth 2.0构建统一认证授权体系

在分布式微服务架构中,服务间安全认证与授权是保障系统安全的核心挑战。OAuth 2.0作为工业级授权框架,通过标准化流程实现资源访问的委托授权,其核心原理是分离认证与授权职责,引入授权服务器、资源服务器等角色。该技术价值在于实现认证逻辑集中化、资源服务无状态化,有效解决微服务场景下用户身份统一识别与权限管控难题。典型应用场景包括前端应用访问后端多服务、服务间内部调用等。本文以Spring Cloud Alibaba生态为基础,结合JWT(JSON Web Token)与Spring Authorizatio

weixin_30764771的博客 468

从零开始搭建SpringCloud微服务框架(二)————Auth认证服务

接着上一节写着走,微服务的原理就是将一个系统拆分为更细致的各个模块,比如认证是个单独的服务,文件上传也可以是个单独的服务...然后注册到Eureka服务中心,这样,各个服务都可以互相调用,如下图 新建springcloud_auth服务 和之前一样,照猫画虎 此时的父工程又多了一个auth子模块,然后再新建启动类,测试接口,pom, application配置文件: 代码:分别是: package com.springcloud; import org.sprin.

BigBossc的博客 2756

Spring Cloud 微服务中搭建 OAuth2.0 认证授权服务

在使用 Spring Cloud 体系来构建微服务的过程中,用户请求是通过网关(ZUUL 或 Spring APIGateway)以 HTTP 协议来传输信息,API 网关将自己注册为 Eureka 服务治理下的应用,同时也从 Eureka 服务中获取所有其他微服务的实例信息。搭建 OAuth2 认证授权服务,并不是给每个微服务调用,而是通过 API 网关进行统一调用来对网关后的微服务做前置过滤,...

javaQQ561487941的博客 1312

Spring Cloud OAuth2 认证服务器

Spring Cloud OAuth2 是 Spring Cloud 体系对OAuth2协议的实现,可以用来做多个微服务的统一认证(验证身份合法性)授权(验证权限)。通过向OAuth2服务(统一认证授权服务)发送某个类型的grant_type进行集中认证和授权,从而获得access_token(访问令牌),而这个token是受其他微服务信任的。............

凉茶铺的博客 3342

整合spring cloud云架构 - SSO单点登录之OAuth2.0登录认证(1)

之前写了很多关于spring cloud的文章,今天我们对OAuth2.0的整合方式做一下笔记,首先我从网上找了一些关于OAuth2.0的一些基础知识点,帮助大家回顾一下知识点:   一、oauth中的角色 client:调用资源服务器API的应用 Oauth 2.0 Provider:包括Authorization Server和Resource Server (1

qq_40354025的博客 2万+

微信DAT图片解密全攻略:一键转换JPG/PNG/GIF

本文详细解析了微信电脑版中DAT图片的加密原理与存储路径,并提供了从定位文件到使用专业工具进行一键解密的完整操作指南。通过简单的步骤,用户可将加密的DAT文件无损还原为JPG、PNG或GIF格式,有效解决无法直接查看聊天图片的难题,同时兼顾了隐私清理与磁盘空间管理。

hill8的博客 1363

OAuth2.0 实践 Spring Authorization Server 搭建授权服务器 + Resource + Client

OAuth2.0 实践 Spring Authorization Server 搭建授权服务器 + Resource + Client

凡的博客 1万+

OnlyOffice Docker部署实战:解除20连接限制+500M文件上传配置(附中文字体解决方案)

本文详细介绍了OnlyOffice企业级Docker部署的全过程,包括解除20并发连接限制、提升文件上传大小至500MB以及解决中文字体显示问题。通过定制镜像、优化配置和字体安装,帮助技术团队快速搭建高性能的文档协作平台,适用于企业级应用场景。

weixin_26850069的博客 443

SpringCloud项目中,出现项目依赖导入时,提示unknown

在做SpringCloud项目的时候,经常会出现这种问题: 这种情况其实也很容易理解,就是不知道这个东西的版本,给他指定个版本就好了(不知道版本可以去官网查): ...

OUCFSB的博客 1624

北京理工大学计算机学院赵曜,中国进出口银行2016年度拟接收毕业生情况公示...

《中国进出口银行2016年度拟接收毕业生情况公示》由会员分享,可在线阅读,更多相关《中国进出口银行2016年度拟接收毕业生情况公示(5页珍藏版)》请在技术文库上搜索。1、二级(三级)单位二级(三级)单位姓名姓名性别性别学历学历毕业学校毕业学校专业专业 中国进出口银行总行 机关 许凯男硕士研究生北京大学法学 中国进出口银行总行 机关 冯晨男硕士研究生北京大学教育技术学 中国进出口银行总行 机关 刘鹏...

weixin_42168902的博客 4274

QMT与通达信代码实战:从预警到交易的自动化实现

本文详细介绍了如何利用QMT量化交易平台与通达信软件实现从预警到交易的全自动化。通过读取通达信预警生成的板块文件,QMT策略可自动执行买卖指令,有效解决手动交易滞后问题。文章提供了完整的代码框架、核心原理拆解及实盘注意事项,帮助投资者构建高效、纪律性的自动化交易系统。

ansible6ops的博客 648

谷粒商城正式的第一天遇到“org.springframework.cloud:spring-cloud-starter-openfeign:jar:unknown was not found”

【代码】谷粒商城正式的第一天遇到“org.springframework.cloud:spring-cloud-starter-openfeign:jar:unknown was not found”

m0_50860573的博客 1597

保姆级教学:从0搭建微信小程序SpringBoot+Vue(一)

目标:实现一个微信小程序从后端数据库MySQL获取的商品展示页。 框架:后端采用SpringBoot,前端采用Vue,数据库MySQL。 部署工具:IntelliJ IDEA 2024.2专业版+HbuilderX+Node+微信开发者工具,jdk1.8已安装

weixin_44545610的博客 4925

一文读懂Springy-Store-Microservices:Spring Cloud微服务架构全景与8大组件深度解析

Springy-Store-Microservices 是一个基于 Spring Boot 与 Spring Cloud 构建的完整微服务实战项目,用一套"网上商店"业务演示云原生微服务架构:API 网关、服务注册发现、配置中心、OAuth2 授权、响应式编程、事件驱动(RabbitMQ/Kafka)与分布式链路追踪(Zipkin)一应俱全。对于想系统学习 Spring Cloud 微服务架构的新

gitblog_01068的博客 465

YOLO11全网首发:CVPR2026 MixerCSeg | DEGConv方向引导边缘门控,破解细长裂缝检测难题

DEGConv通过方向先验嵌入、边缘增强卷积和动态门控三大机制,针对性解决了YOLO在处理裂缝类细长、多方向、低对比度目标时的特征提取不足问题,显著提升了裂缝检测的精度与鲁棒性。

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 561

向华为学习——IPD流程体系之IPD术语

《IPD体系核心概念与业务术语解析》摘要: IPD(集成产品开发)是一种以市场为导向的结构化产品开发管理模式,通过跨部门协作、异步开发、CBB(通用构建模块)和管道管理等手段,实现产品全生命周期高效管理。体系包含七大核心要素:跨部门团队(如IPMT决策层、PDT执行层)、结构化流程(分阶段评审)、端到端项目管理(WBS分级计划)、客户需求分析、投资组合优化及质量管控(TR技术评审)。各业务领域术语涵盖财务(NPV、IRR)、开发(需求分解、基线化)、制造(可制造性设计)、采购(Sourcing团队)及市场(

cdfunlove的博客 481

大肥鱼AstrBot:会看会听有记忆还会主动找你的QQ机器人,AstrBot+DeepSeek全栈AI陪伴全家桶完全解析

**大肥鱼AstrBot**(dafeiyu-astrbot)是一个开箱即用的 **AstrBot QQ 机器人**开源项目:基于 **AstrBot + NapCat + DeepSeek + 阿里云百炼**,把一只"住在 QQ 里的蓝色鲸鱼娘"完整搬进你的聊天窗口——她能看图片视频、听语音、发真 QQ 表情、用语音条说话、拥有长期记忆,还会主动找你看 B 站、催你睡觉。 [![大肥鱼Astr

gitblog_00099的博客 687

面向红外小目标检测的SCTransNet:模型优势解析、代码实现与完整复现指南

摘要:本文详细介绍了基于SCTransNet的红外小目标检测全流程实践方案。针对红外小目标检测面临的三大挑战(特征稀缺、背景干扰、尺度变化),SCTransNet通过空-通道交叉注意力机制有效增强目标特征。文章包含完整的PyTorch实现代码,涵盖特征提取、注意力模块、多尺度融合等核心组件,并提供模型训练、评估的具体方法。同时给出毕设创新方向的建议,如模型轻量化、多模态融合等,帮助提升研究深度。该方案技术难度适中,应用价值明确,是红外目标检测领域理想的毕设选题方向。

m0_71589036的博客 4759

SpringCloud整合spring security+ oauth2+Redis实现认证授权

在微服务构建中,我们一般用一个父工程来通知管理依赖的各种版本号信息。父工程pom文件如下: 构建eureka注册中心 在SpringCloud微服务体系中服务注册中心是一个必要的存在,通过注册中心提供服务的注册和发现。具体细节可以查看我之前的博客,这里不再赘述。我们开始构建一个eureka注册中心,对应的yml配置文件如下: 对应的项目启动类代码如下: 至此,一个单体的服务注册中心搭建完成。上文我们已经完成了注册中心的搭建,接下来我们开始搭建认证授权中心。我们同样在父工程下面新建一个子工程,作为认证授权中心

write less , do more 2万+

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

微服务架构演进:spring-boot-microservices-series从单体到分布式的完整改造路径

spring-boot-microservices-series是一个基于Spring Boot和Spring Cloud的微服务实践项目,通过完整的改造路径展示了如何从传统单体应用平滑过渡到弹性分布式系统。本项目提供了可直接运行的微服务架构代码示例,包含服务注册与发现、配置中心、熔断机制、分布式追踪等核心组件,是学习微服务架构的理想实践案例。 ## 微服务架构核心组件解析 ### 服务注册与

gitblog_00303的博客 1039

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring Authorization Server 1.1 扩展实现 OAuth2 密码模式与 Spring Cloud 的整合实战

本文基于开源微服务商城项目 youlai-mall、Spring Boot 3 和 Spring Authorization Server 1.1 版本,演示了如何扩展密码模式,以及如何将其应用于 Spring Cloud 微服务实战。

有来技术 1万+

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Tensor2Tensor 自定义模型开发指南:从零构建并注册你自己的 T2TModel

本文基于 Tensor2Tensor 官方文档 [docs/new_model.md](https://link.gitcode.com/i/e598fff20655d4498ab36b3dcd3d5f5a) 编写,系统讲解如何在 T2T 框架中创建、注册并训练一个完全自定义的深度学习模型。你将掌握 `T2TModel` 抽象基类的三种典型用法(Estimator、Layer、Inference)

gitblog_01075的博客 676

Spring Security实现OAuth2协议及实战

OAuth2是目前最流行的授权协议,用来授权第三方应用,获取用户数据。举个例子:快递员想要进入小区,有3种方式。1是业主远程开门,2是业主告诉门禁密码,3是使用令牌(Oauth2)。如图:令牌和密码的区别:令牌相当于火车票,密码相当于是钥匙。令牌是短期的,自动失效。密码是长期有效。令牌是可以撤销的,撤销立即生效。密码一般不允许他们撤销。令牌有权限范围,如车票座位为10车A15座。密码一般是完整权限。第三方登录演示(网易云客户端利用QQ扫码登录)

qq_43372633的博客 3005

Gatsby 站点接入 TypeScript 全指南:gatsby-plugin-typescript 的配置、使用与编译原理剖析

本篇指南围绕当前仓库 [plugins/gatsby-plugin-typescript](https://link.gitcode.com/i/3790ab212102c598a91cdff86240c80b) 插件展开,讲解如何在 Gatsby 站点中一键开启 TypeScript / TSX 支持:从安装依赖、在 `gatsby-config.js` 中注册插件、在根目录编写 `tsconf

gitblog_00720的博客 1011

Spring Cloud:认证 授权 OAuth2、JWT

OAuth2 OAuth2是当前授权的行业标准,其重点在于为Web应用程序、桌面应用程序、移动设备以及室内设备的授权流程提供简单的客户端开发方式。它为第三方应用提供对HTTP服务的有限访问,既可以是资源拥有者通过授权允许第三方应用获取HTTP服务,也可以是第三方以自己的名义获取访问权限。 角色 OAuth2中主要分为了4种角色: Resource Owner(资源所有者),是能够对受保护的资源授予访问权限的实体,可以是一个用户,这时会称为终端用户(end-user)。 Resource Server(资源

泛泛之素 7249
上一篇: 学习笔记:微服务-8 ngnix+zuul 实现高可用负载均衡
下一篇: 学习笔记:微服务10 spring cloud config server配置中心
领尚
博客等级 码龄14年 1143粉丝 271原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值