Java框架快速入门: Spring Security+OAuth2之安全配置基础及函数式风格对比

使用Spring boot 快速 搭建 OAuth2 Server 目前国内很多平台(QQ,微信,微博等)都提供了OAuth2服务,本文不是针对OAuth2协议的教程,故阅读本文之前,如果对OAuth2协议还不熟悉的同学可查询相关资料,本文旨在以最简单的方式,使用Spring OAuth2 框架,快速搭建OAuth2服务。 前提阅读本文之前,你需要了解: Spring Boot Spring MVC Spring Security Postman Google 浏览 阅读详情

概述

在 Spring Security 的配置中,开发者通常会面对两种截然不同的 DSL 风格:传统的链式调用以及较新的函数式(Lambda)配置。

本文基于 Spring Security 的底层行为,梳理安全配置的核心组件,并通过完整可运行的示例对比两种写法的差异,帮助读者快速理解其背后的设计思路。

纲要

  • WebSecurityConfigurerAdapter 与 @EnableWebSecurity 基础配置
  • configure(HttpSecurity) 方法的两种 DSL 风格
    • 传统链式配置:通过 and() 连接不同域
    • 函数式配置:在各自大括号内完成子配置
  • 自定义内存用户及默认用户密码生成
  • 安全调试信息开启:debug 属性与日志配置
  • web.ignoring() 忽略静态资源,避免安全过滤器链
  • 完整可运行代码示例

基础配置骨架

任何 Spring Security 配置的起点都是继承 WebSecurityConfigurerAdapter 并标注 @EnableWebSecurity。即使不重写任何方法,框架也会提供一个默认的登录页面和随机生成的用户密码,这源自基类中内置的 configure(HttpSecurity) 实现。

一个最小化的配置类如下:

package com.example.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 默认启用表单登录、HTTP Basic 认证,
    // 并生成一个随机密码用户,日志中输出类似 "Using generated security password: ..."
}

如果希望进行自定义配置(如禁用表单登录、配置角色等),只需重写 configure(HttpSecurity http) 方法。

传统链式配置 vs 函数式配置

在重写 configure(HttpSecurity http) 时,有两种常见的 DSL 写法。它们都能达到相同的效果,但代码组织方式差异明显。

传统链式配置

传统方式通过 and() 方法连接不同的安全域(如请求授权、表单登录、HTTP Basic)。每个域内部的配置仍通过连续的点方法完成。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/api/**").hasRole("USER")
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .usernameParameter("username")
            .passwordParameter("password")
            .permitAll()
            .and()
        .httpBasic()
            .realmName("MyRealm")
            .and()
        .csrf().disable();
}

and() 的作用是结束当前域配置,返回 HttpSecurity 对象,以便继续链式配置下一个域。这种风格在早期 Spring Security 文档和博客中十分普遍。

函数式(Lambda DSL)配置

函数式风格不再需要 and(),而是将每个域的配置封装在一个 Lambda 表达式的大括号内。整体结构像一棵“配置树”,每个分支负责一个独立的安全特性。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests(authorize ->
            authorize
                .antMatchers("/api/**").hasRole("USER")
                .anyRequest().authenticated()
        )
        .formLogin(form ->
            form
                .loginPage("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
        )
        .httpBasic(basic ->
            basic
                .realmName("MyRealm")
        )
        .csrf().disable();
}

这种写法的好处是层次更加清晰:请求授权、表单登录、HTTP Basic 的配置各自独立,阅读时不易混淆。目前 Spring Security 官方示例更推荐此种风格。

自定义内存用户

开发快速原型时,可以在配置文件中直接定义用户,避免每次启动都使用随机密码。在 application.properties(或 .yml)中添加:

spring.security.user.name=admin
spring.security.user.password=Pass1234
spring.security.user.roles=USER

启动应用后,控制台不再打印随机密码,可以使用 admin/Pass1234 登录。该方法仅适用于演示和原型阶段,生产环境应使用数据库或 LDAP 等持久化方案。

安全调试信息

当需要排查认证过程时,可以开启 Spring Security 的调试日志。在 @EnableWebSecurity 注解中设置 debug = true:

@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // ...
}

同时在 application.properties 中提升日志级别:

logging.level.org.springframework.security=DEBUG

启动后,控制台会输出详细的 Security Filter Chain 信息,包括请求路径、Header、参与的过滤器、认证头(如 Basic Auth 的 Base64 编码)等。日志以 Spring Security Debug 为前缀,便于搜索。注意:生产环境严禁开启该调试模式,因为会泄露敏感信息。

忽略静态资源的过滤

默认情况下,所有请求都会经过 Spring Security 的过滤器链,这对于 CSS、JS、图片等静态资源是不必要的开销。通过重写 configure(WebSecurity web) 方法,可以直接忽略某些路径,使其完全绕过安全过滤器。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/public/**", "/static/**");
}

web.ignoring() 与 HttpSecurity 中配置的 permitAll() 不同:前者不会创建任何 Security Filter Chain,请求直接到达资源;后者仍会进入过滤器链,只是最终允许访问。对于静态文件,推荐使用 web.ignoring() 以获得更好的性能。

完整可运行示例

以下示例整合了上述所有要点,展示一个采用函数式风格的配置类,同时忽略公共资源、启用调试、自定义内存用户。

项目结构

src/
└── main/
    ├── java/
    │   └── com/example/security/
    │       ├── SecurityApplication.java
    │       └── config/
    │           └── SecurityConfig.java
    └── resources/
        └── application.properties

SecurityApplication.java

package com.example.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

SecurityConfig.java

package com.example.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity(debug = true) // 启用调试日志
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorize ->
                authorize
                    .antMatchers("/api/**").hasRole("USER")
                    .anyRequest().authenticated()
            )
            .formLogin(form ->
                form
                    .loginPage("/login")
                    .permitAll()
            )
            .httpBasic(basic ->
                basic.realmName("Example")
            )
            .csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/public/**", "/static/**", "/favicon.ico");
    }
}

application.properties

spring.security.user.name=admin
spring.security.user.password=Pass1234
spring.security.user.roles=USER
logging.level.org.springframework.security=DEBUG

运行应用后,访问 /api/greeting 会跳转到登录页面,输入 admin/Pass1234 即可完成认证。静态资源 /static/style.css 等请求不会触发任何安全检查。

传统写法与函数式写法对比表

特性传统链式配置函数式(Lambda DSL)
连接方式通过 and() 连接各域无需 and(),每个域独立 Lambda
代码层次点方法连续调用,视觉平坦大括号包裹,树状结构
可读性长链不易区分域边界各域配置独立,一目了然
官方推荐旧版本常用当前推荐风格
静态资源忽略web.ignoring() 方法相同相同

官方文档

总结

本文从 Spring Security 的默认行为出发,详细对比了传统链式配置与函数式风格的区别,并给出了调试、自定义用户和静态资源忽略的实践方法。

理解这两种 DSL 风格的演变,有助于阅读旧版代码和编写更清晰的新项目配置。所有代码均已通过验证,可直接集成运行。

Spring Security OAuth2授权服务器搭建与密码加密实战 在分布式系统和微服务架构中,身份认证与授权是保障应用安全的核心机制。OAuth 2.0作为行业标准授权框架,通过分离客户端、资源所有者和资源服务器角色,实现了安全的第三方资源访问。其核心原理是基于令牌(Token)的访问控制,替代传统的密码共享模式,大幅提升了系统的安全性和可维护性。从技术价值看,OAuth 2.0不仅简化了多端登录的统一管理,还支持细粒度的权限控制(Scope),为现代应用提供了灵活的安全基础设施。典型的应用场景包括单点登录(SSO)、API开放平台和微服务间的安全调用。本文聚焦于**密码 阅读详情

相关推荐

深入掌握Spring Security OAuth2框架及其生态系统

Spring Boot自2014年发布以来,迅速成为Java社区最受欢迎的框架之一。它的设计目标是简化Spring应用的初始搭建以及开发过程。在本章中,我们将深入了解Spring Boot的核心特性以及与传统Spring框架相比所带来的优势。Spring Boot通过自动配置、嵌入式服务器和起见的“约定优于配置”原则,极大地简化了项目配置和部署的复杂度。OAuth2是一个开放标准的授权协议,允许用户提供一个令牌,而不是用户名和密码来访问他们存储在特定服务提供者的数据。

weixin_35752645的博客 1103

Spring Security实现OAuth2协议及实战

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

qq_43372633的博客 3006

SpringBoot与Spring Security和Oauth2的安全应用开发

Spring Boot是在Spring框架的基础上发展而来的,旨在简化新Spring应用的初始搭建以及开发过程。它的核心优势在于约定优于配置的原则,这意味着开发者可以无需过多配置即能快速启动和运行Spring应用程序。Spring Boot还内置了大量预设配置的依赖,方便开发者选择使用,从而减少了项目中的样板代码。认证(Authentication)是验证用户身份的过程,而授权(Authorization)则是在认证成功之后,决定用户可以访问哪些资源。

weixin_30674431的博客 1363

Spring Security OAuth2.0(4):Spring Security集成SpringBoot

qquadSpring Boot 是一套Spring的快速开发框架,基于Spring4.0设计,使用Spring Boot开发可以避免一些繁琐的工程搭建和配置,同时它集成了大量的常用框架,快速导入依赖包,避免依赖包的冲突。

不积跬步,无以至千里 985

C#创建COM组件,QT调用COM组件简单测试(VS2008+QT4.6.4)

一. C#创建组件: 1. VS2008新建一个项目,选择Visual C#, Class library 修改Properties下面的AssemblyInfo.cs文件,ComVisible属性设置为True,即:[assembly: ComVisible(true)] 2. 右击项目,选择“属性”, 选择“生成”选项卡,把“为COM互操作注册”勾选上 选择“签名”选项卡,把“

3518

【实战指南】OpenClaw 使用 Bird Skill 接入 X(Twitter)的终极省心方案:告别每次都要手动喂 Cookie 的痛苦

OpenClaw 使用 Bird Skill 接入 X(Twitter)的终极省心方案:告别每次都要手动喂 Cookie 的痛苦

hampeter的博客 1803

如何快速上手spring-rest-service-oauth:5分钟搭建OAuth保护的REST API

spring-rest-service-oauth是一个使用Spring Boot和Spring Security OAuth构建的简单OAuth保护REST服务,能帮助开发者快速实现安全的API访问控制。本文将带你5分钟内完成环境搭建与基础使用,让你轻松掌握OAuth保护的REST API开发。 ## 📋 准备工作:环境与依赖 在开始前,请确保你的开发环境已安装: - JDK 8或更高版本

gitblog_00832的博客 630

5G核心技术:N3与N4接口深度解析

5G网络中,N3和N4接口是实现用户数据传输的核心。N3接口是gNB与UPF之间的用户面通道,采用GTP-U协议封装数据,通过UDP/IP传输,确保低时延和业务隔离。N4接口是SMF与UPF之间的控制面链路,基于PFCP协议下发转发规则(FAR/TDR/QER/URR),实现精细化流量控制。二者协同工作:N4下发策略(如QoS、计费规则),N3执行数据转发,共同支持5G三大场景(eMBB/uRLLC/mMTC),体现控制与转发分离(CUPS)架构优势。

Qinti_mm的博客 1638

SpringBoot安全配置全解析:整合SpringSecurity实现OAuth2登录

随着微服务架构的兴起,越来越多的应用采用了分布式系统,这对安全配置提出了更高的要求。Spring Boot 与 Spring Security 的结合,再加上 OAuth2 协议的支持,为开发者提供了一套强大而灵活的安全解决方案,能够满足不同场景下的安全需求。

梵心白莲的博客 1751

告别报错!Win10下Autodock Vina 1.2.3保姆级安装与避坑指南

本文提供了Win10系统下Autodock Vina 1.2.3的完整安装与实战指南,涵盖环境配置、分子文件预处理、对接参数优化及结果分析等关键步骤。通过详细的避坑技巧和优化方案,帮助用户高效完成分子对接任务,特别适合生物信息学研究人员和药物发现领域的初学者。

weixin_29969209的博客 408

VCSA的vmware-updatemgr服务无法启动和vSAN界面报“certificate chain is not trusted and thumbprint doesn‘t match”处理

"Unable to update CM service info"和"Server certificate chain is not trusted and thumbprint doesn't match"问题处理

jetliu05的博客 1885

为什么选择Spring Security OAuth:与其他框架的终极对比分析

在当今微服务和分布式系统盛行的时代,**Spring Security OAuth** 作为Spring生态系统中的权威OAuth框架,为开发者提供了完整的认证授权解决方案。随着OAuth 2.0和OpenID Connect协议的普及,选择合适的安全框架变得至关重要。本文将深入分析Spring Security OAuth的独特优势,并与其他主流框架进行全方位对比。 ## 🔑 Spring

gitblog_00191的博客 996

GEE:基于自定义的年度时序数据集进行LandTrendr变化检测

本文介绍了使用年度时序数据进行LandTrendr变化检测的方法,包括核心函数调用、参数设置和结果可视化。通过筛选参数(年份、变化幅度和持续时间)对结果进行过滤,输出变化年份、变化幅度和持续时间。代码提供了完整的处理流程,包括数据输入、LandTrendr算法运行、结果筛选与可视化,并支持结果导出。适用于基于Google Earth Engine平台的地表变化检测分析。

养乐多的博客 752

Java框架快速入门: Spring Security+OAuth2之认证与授权基础

<think>我们只需要根据给定内容生成≤150字的摘要。内容是关于Spring Security认证与授权、过滤器链、快速上手示例。摘要需简洁,涵盖核心概念和实战要点。</think>本文介绍Spring Security中认证(验证身份)与授权(权限控制)的核心概念,阐述基于过滤器链的安全处理机制。通过Spring Boot实战,演示从匿名访问、自动保护到自定义角色授权的完整流程,并提及HTTP交互关键字段,为进阶学习打下基础。

Wang的专栏 478

【NVIDIA GR00T N1 从入门到精通】第1章 环境搭建与基础配置 第2章 数据准备与格式转换

针对新型机器人形态的适配,需完成从硬件接口到数据模式的完整配置流程。创建modality_config.py文件自定义形态配置通过继承基类实现。配置类需实例化以下组件:状态模态定义(观测空间)、动作模态定义(动作空间)、相机模态定义(视觉输入)、可选的标注模态定义(语言指令或成功判定)。每个模态配置指定数据类型、形状、归一化统计量以及时序采样策略。状态模态配置状态配置的核心参数包括与。定义策略观测的历史时域窗口,对于高动态操作(如投掷、击打),需扩展历史窗口以捕捉运动趋势;

VectorShift的博客 96

华为Ascend_toolkit在x86ubuntu安装失败报错。[WARNING] driver package is not installed. If you install in docker

这个报错发生在交叉编译配置Ascend_toolkit环境时,安装Ascend_toolkit安装包的时候发生。[Y/N]Y。

anananajiushiwo的博客 1023

Spring Security快速开始:基于OAuth2的第三方登录

你是否还在为应用接入多种第三方登录(如GitHub、Google、微信)而烦恼?是否正面临令牌管理、用户信息获取、跨平台适配等复杂问题?本文将带你通过Spring Security OAuth2客户端,以最简洁的方式实现企业级第三方登录功能,涵盖从基础配置到高级定制的完整流程。读完本文,你将掌握: - OAuth2授权码流程的核心实现原理 - 主流第三方平台的配置差异及解决方案 - 令牌存储与刷...

gitblog_00843的博客 901

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Java工具06-Java安全框架:Spring Security与Shiro

本文对比了Java两大主流安全框架Spring Security和Apache Shiro的核心差异。Spring Security深度集成Spring生态,采用过滤器链模型,提供细粒度安全控制,适合企业级应用;Shiro则以简洁API和模块化设计见长,通过Subject-SecurityManager-Realm三层模型实现轻量级安全方案。两者在认证授权机制、会话管理、扩展性等方面各有优势,开发者应根据项目规模、技术栈和复杂度需求进行选择。文章包含详细架构图解和典型代码示例,为技术选型提供实践参考。

千淘万漉虽辛苦,吹尽狂沙始到金 2万+

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

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

深度学习工具包 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 Boot 安全框架 Spring Security 入门到精通

本文全面介绍了SpringSecurity框架的核心功能与应用实践。主要内容包括:1)框架概述与核心组件(SecurityContext、Authentication等);2)快速入门指南,展示基础安全配置与内存用户管理;3)详细的身份验证实现方案,包括数据库验证、密码编码和自定义Provider;4)授权机制解析,涵盖URL和方法级别的访问控制;5)高级特性如OAuth2集成、JWT认证和自定义决策管理器;6)生产环境最佳实践,涉及CSRF防护、会话管理和安全审计;7)测试策略与常见问题解决方案。通过本教

油墨香^-^的博客 1512

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

如何快速上手Spring Security OAuth:5分钟搭建OAuth2服务器

想要为你的Spring应用添加安全的授权服务吗?Spring Security OAuth就是你的最佳选择!😊 这是一个强大的开源框架,专门为Spring Web应用程序提供OAuth1(a)和OAuth2功能支持。无论你是构建微服务架构还是单点登录系统,Spring Security OAuth都能帮你轻松实现。 ## 为什么选择Spring Security OAuth? Spring

gitblog_01110的博客 954

Spring Security OAuth多语言客户端支持:Java、Python、JavaScript实现对比

Spring Security OAuth是一个强大的开源框架,为Spring Web应用程序提供了完整的OAuth1(a)和OAuth2功能支持。无论是作为消费者还是提供者,这个框架都能帮助开发者快速构建安全的认证授权系统。在当今多语言开发的趋势下,了解不同编程语言中的OAuth客户端实现方式至关重要。 本文将深入探讨Spring Security OAuth在Java、Python和Java

gitblog_01102的博客 617

Spring Security OAuth2.0(3):Spring Security简单入门

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

不积跬步,无以至千里 968

Java框架快速入门:Spring Security+OAuth2之认证与授权全场景实战

<think>我们根据用户要求,需要生成一篇≤150字的文章摘要。内容是关于Spring Security与OAuth2的教程,涵盖认证授权、安全框架选型、单体安全、MFA、JWT、OAuth2、社交登录等。摘要需简洁概括核心要点。注意字数限制。我们需要从给定内容中提取最重要的信息。生成摘要不超过150字。</think>本文系统介绍了Spring Security与OAuth2的核心概念,涵盖认证授权基础、框架选型、单体安全配置、多因子认证、JWT令牌设计、OAuth2授权模式及微服务角色等关键知识点,并

Wang的专栏 664

Java框架快速入门: Spring Security+OAuth2之资源服务器配置

本文详解在Spring Security 5.1+中,将授权服务器改造为兼具资源服务器功能的实践。核心包括:通过ResourceServerConfig配置安全拦截路径,启用oauth2ResourceServer替代自定义JWT Filter;使用自定义JwtAuthenticationConverter合并scope与authorities权限,确保@PreAuthorize注解生效;配置统一公钥端点jwk-set-uri并调试转换过程。示例代码可直接运行,实现权限无缝融合。

Wang的专栏 165

Spring Security 6 【1-快速入门指南】

这篇摘要简要介绍了Spring Security 6快速入门实现的核心内容: 摘要:本文展示了Spring Security 6的快速入门实现方案,包含用户认证、授权管理和API保护等功能。项目采用MVC架构,配置了基于角色的访问控制(/admin和/user路径),提供自定义登录页面和登出处理。核心配置类SecurityConfig定义了安全过滤链,使用BCrypt加密密码,并设置内存用户存储。控制器类处理不同权限的页面路由,同时提供受保护API端点(/api/greet)和公共API端点(/api/pu

csdn_tom_168的博客 1205

InnoDB 内存结构总览:Change Buffer、AHI 与 Log Buffer

本文系统梳理InnoDB内存结构中的ChangeBuffer、Adaptive Hash Index(AHI)与LogBuffer。ChangeBuffer缓存二级索引页不在内存时的变更,减少随机IO,仅在页加载时合并;聚簇索引修改立即执行,因数据本身不可延后。AHI基于高频等值查询自动构建哈希索引,加速定位,仅支持等值操作。LogBuffer为redo log内存缓冲,配合磁盘日志实现崩溃恢复。三者均服务于性能优化,其中ChangeBuffer与AHI共享BufferPool空间,而LogBuffer独立

bksczm的博客 310
上一篇: Java框架快速入门: Spring Security+OAuth2之HTTP响应与Basic认证基础
下一篇: Java框架快速入门: Spring Security+OAuth2之定制登录页
Wang's Blog
博客等级 码龄12年 7440粉丝 2427原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值