# SpringBoot Security中OAuth2.0简单示例是怎样的 ## 引言 在现代Web应用开发中,安全认证是至关重要的环节。OAuth2.0作为当前主流的授权框架,与Spring Security的集成能够为SpringBoot应用提供强大的安全保护。本文将详细介绍如何在SpringBoot项目中通过Spring Security实现OAuth2.0的基础认证流程,包含完整的代码示例和配置说明。 --- ## 一、OAuth2.0基础概念 ### 1.1 什么是OAuth2.0 OAuth2.0是一种**开放授权标准**,允许用户在不暴露密码的情况下,让第三方应用访问其在服务提供者上的资源。主要包含以下角色: - **资源所有者(Resource Owner)**:通常是终端用户 - **客户端(Client)**:请求访问资源的应用 - **授权服务器(Authorization Server)**:颁发访问令牌 - **资源服务器(Resource Server)**:托管受保护资源 ### 1.2 四种授权模式 1. 授权码模式(最安全) 2. 简化模式(Implicit) 3. 密码模式(Resource Owner Password Credentials) 4. 客户端模式(Client Credentials) --- ## 二、环境准备 ### 2.1 项目初始化 使用Spring Initializr创建项目,添加依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/login**").permitAll() .anyRequest().authenticated() .and() .oauth2Login(); } } Client ID和Client Secrethttp://localhost:8080/login/oauth2/code/githubspring: security: oauth2: client: registration: github: client-id: your-client-id client-secret: your-client-secret scope: user:email @RestController public class UserController { @GetMapping("/user") public String user(Principal principal) { return "Hello, " + principal.getName(); } } @Bean public PrincipalExtractor principalExtractor() { return map -> { String login = (String) map.get("login"); return new CustomUser(login, (String) map.get("name")); }; } spring: security: oauth2: client: registration: github: { ... } google: client-id: google-client-id client-secret: google-secret scope: email,profile <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> spring: security: oauth2: resourceserver: jwt: issuer-uri: https://auth-server.com jwk-set-uri: https://auth-server.com/.well-known/jwks.json @Configuration @EnableWebSecurity public class ResourceServerConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/public").permitAll() .antMatchers("/api/**").authenticated() .and() .oauth2ResourceServer() .jwt(); } } http://localhost:8080/userGET /api/private HTTP/1.1 Host: localhost:8080 Authorization: Bearer <access_token> @Bean CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } 实现OAuth2AuthorizationFailureHandler处理失效令牌
通过本文的示例,我们实现了: 1. SpringBoot与OAuth2.0的基本集成 2. GitHub作为第三方认证提供商 3. 资源服务器的JWT验证配置
完整代码示例可在GitHub仓库获取。实际项目中还需考虑会话管理、权限控制等进阶功能。
扩展阅读建议: - Spring Security官方文档 - OAuth2.0 RFC 6749规范 - OpenID Connect协议 “`
注:本文示例基于Spring Boot 2.7.x + Spring Security 5.x版本,实际开发时请根据使用的框架版本调整配置方式。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。