使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)
前言
要解决的问题:不暴露客户密码的情况下授权三方服务访问客户资源
角色:资源拥有者,客户端应用(三方服务),授权服务器,资源服务器
模式:授权码模式:需要客户授权得到授权码后再次通过三方服务的密码取得token,双重校验,最安全,最复杂
简易模式:无需授权码对用户暴露返回的Token,不安全
密码模式:客户端应用需要资源拥有者密码。全链路可信情况下使用
客户端模式:无需资源拥有者密码,只需要客户端应用密码进行校验,服务器对服务器使用
本试验主要演示注册码模式,分为授权服务器和资源服务器俩个应用,后续会持续扩展为单个授权服务器和多个资源服务器。
试验步骤
按照以下截图创建授权服务器,授权服务器包结构如下
1 使用pom文件导入相应依赖,主要导入了以下依赖包
1)SpringBoot的security和web,
2)SpringSecurity的OAuth2
pom文件如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>io.spring2go</groupId><artifactId>authcode-server</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>authcode-server</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.10.RELEASE</version><relativePath /> <!-- lookup parent from repository --> </parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- for OAuth 2.0 --><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
2 修改application.properties设置用户登录密码
# Spring Security Setting security.user.name=bobo security.user.password=xyz
3 制作SpringBoot的启动文件
package com.test.authcodeserver;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class AuthCodeServerApplication {public static void main(String[] args) {SpringApplication.run(AuthCodeServerApplication.class, args);} }
4 设置授权服务代码
package com.test.authcodeserver.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;@Configuration @EnableAuthorizationServer public class AuthCodeServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");}@Override public void configure(ClientDetailsServiceConfigurer clients)throws Exception {//JdbcClientDetailsService可以动态管理数据库中客户端数据 //http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo clients.inMemory().withClient("testclientid")//clientId:(必须的)用来标识客户的Id。 .secret("1234")//secret:(需要值得信任的客户端)客户端安全码,如果有的话。 .redirectUris("http://localhost:9001/authCodeCallback")//客户端应用负责获取授权码的endpoint .authorizedGrantTypes("authorization_code")// 授权码模式 .scopes("read_userinfo", "read_contacts");//scope:用来限制客户端的访问范围,如果为空(默认)的话,那么客户端拥有全部的访问范围。 }}
5 启动SpringBoot服务
6 客户端服务访问授权服务器,铜鼓访问如下url取得授权码
http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo
访问完成后会redirect回客户端服务器并将授权码作为参数传回,其中localhost:9001即为客户端应用
7 客户端使用返回的授权码获取访问令牌
发送请求参数如下
url:http://localhost:8080/oauth/token
code=ifz2BV&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A9001%2FauthCodeCallback&scope=read_userinfo
得到的令牌数据
}
以上授权服务器就简单完成了,下面将制作资源服务器
--------------------------------------------------------------------------------------------------
资源服务器
0 资源服务器的包结构
1 资源服务器配置,使用RemoteTokenServices调取认证服务器的认证方法来对Token进行认证
package com.test.resourceserver.config;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.RemoteTokenServices; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; import org.springframework.security.web.AuthenticationEntryPoint;import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;//资源服务配置 @Configuration @EnableResourceServer public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {@Primary @Bean public RemoteTokenServices tokenServices() {final RemoteTokenServices tokenService = new RemoteTokenServices();tokenService.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");tokenService.setClientId("testclientid");tokenService.setClientSecret("1234");return tokenService;}@Override public void configure(HttpSecurity http) throws Exception {// http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // .and() // .authorizeRequests() // .anyRequest() // .authenticated() // .and() // .requestMatchers() // .antMatchers("/api/**"); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().authorizeRequests().anyRequest().permitAll();} }
2 提供对外的API接口
package com.test.resourceserver.api;import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;@Controller public class UserController {// 资源API @RequestMapping("/api/userinfo")public ResponseEntity<UserInfo> getUserInfo() {String user = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();String email = user+ "@test.com";UserInfo userInfo = new UserInfo();userInfo.setName(user);userInfo.setEmail(email);return ResponseEntity.ok(userInfo);}}
调用getUserInfo
http://localhost:8004/api/userinfo
authorization: Bearer 638aa01c-4ccd-4873-ab86-d46f22aea091
调用后返回资源服务器的结果
至此一个资源服务器和认证服务器分离的资源调用就结束了。
使用SpringSecurity 实现 OAuth2 资源服务器认证服务器分离( 注册码模式)相关推荐
- 利用Wifidog实现微信wifi连接以及自写认证服务器
前言 大家如果有用公共场合wifi的习惯,想必都有过如下的体验. 这就是利用微信身份来进行wifi连接认证,主要目的是商家为了吸引顾客,推广其公众号.别的也不多说,下面就来讲一讲怎么实现这样的wifi ...
- SpringSecurity+JWT+OAuth2
一个简洁的博客网站:http://lss-coding.top,欢迎大家来访 学习娱乐导航页:http://miss123.top/ 1. Spring Security 简介 1.1 概述 什么是安 ...
- SpringBoot实现OAuth2认证服务器
一.最简单认证服务器 1. pom依赖 <dependency><groupId>org.springframework.boot</groupId><art ...
- 搭建认证服务器 - Spring Security Oauth2.0 集成 Jwt 之 【授权码认证流程】 总结
在搭建介绍流程之前,确保您已经搭建了一个 Eureka 注册中心,因为没有注册中心的话会报错(也有可能我搭建的认证服务器是我项目的一个子模块的原因):Request execution error. ...
- 认证服务器,资源服务器
oauth2.0–基础–03–简单搭建认证服务器,资源服务器 代码文章 https://gitee.com/DanShenGuiZu/learnDemo/tree/master/auth2.0--le ...
- OAuth 2.0实现分布式认证授权-jwt的认证服务器和资源服务器配置(5)
一 jwt 1.1 jwt? JSON Web Token ( JWT )是一个开放的行业标准( RFC 7519 ),它定义了一种简介的.自包含的协议格式,用于 在通信双方传递json对象 , 传递 ...
- oauth过滤login_OAuth2AuthenticationProcessingFilter资源认证服务器过滤器
资源服务器如何认证访问身份? 一般会传入access_token,那资源认证服务器是如何解析令牌以及如何与资源认证服务器的token库进行对比的? 核心代码在org.springframework.s ...
- Spring Security oAuth2创建认证服务器模块
POM <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http:// ...
- Oauth2.0 认证服务器搭建
核心 POM <dependency><groupId>org.springframework.cloud</groupId><artifactId>s ...
- Spring Cloud OAuth2 认证服务器
1.Spring Cloud OAuth2介绍 Spring Cloud OAuth2 是 Spring Cloud 体系对OAuth2协议的实现,可以用来做多个微服务的统一认证(验证身份合法性)授权 ...
最新文章
- 封装了一套WeCenter的IOS SDK
- python – 在循环中创建不同的变量名
- mysql的innodb数据库引擎详解
- Ubuntu 14.04 LTS, 64bit, cuda 7, Caffe环境配置编译和安装
- (13)Zynq DDR控制器介绍
- Junit + Mockito 使用资料整理
- jquery手机端带农历的万年历插件
- 如何通过股票量化交易接口实现盈利稳定?
- Intellij idea keymap
- 2020-2021阿里巴巴Java面试真题解析
- Java学习方法——类的构造方法
- 非常实用的10款网站数据实时分析工具(强烈推荐)
- 计算机网络第一章概论
- word生成目录右对齐
- 骞云再获阿里云产品生态集成认证,携手共建云原生管理新生态
- JavaScript定时器-限时秒杀
- java 0x03 和0x0a
- 上传身份证照片js_js上传身份证正反面
- 关于unity3D人物存在刚体的情况下移动时出现抖动的问题
- DISM 操作系统包 (.cab 或.msu) 服务命令行选项
热门文章
- Flutter 模拟神舟十三号火箭发射动画
- 基于DS-lite的IP城域网向IPv6演进过渡方案研究
- 高德地图记录跑步轨迹_朋友圈晒跑步 亲测高德地图和百度地图哪个更实用
- SPSS应用程序无法启动,因为应用程序的并行配置不正确。请参阅应用程序事件日志,或使用命令行sxstrace.exe工具。
- 用pdf转cad转换器进行操作的简单步骤
- doe五步法_DOE方法介绍
- 工艺过程卡片,工序卡片,工艺卡,刀具卡区别
- EFK家族---Fluentd日志收集
- Oracle数据库安装教程--Oracle19c DataBase
- 虚幻4UE4使用PS4 DualShock4手柄ProController Switch手柄