oauth2.0授权码模式详解
Python微信订餐小程序课程视频
https://edu.csdn.net/course/detail/36074
Python实战量化交易理财系统
https://edu.csdn.net/course/detail/35475
oauth2.0授权码模式
欢迎关注博主公众号「Java大师」, 专注于分享Java领域干货文章http://www.javaman.cn/sb2/oauth-code
授权码(authorization code)方式,指的是第三方应用先申请一个授权码,然后再用该码获取令牌。
这种方式是最常用的流程,安全性也最高,它适用于那些有后端的 Web 应用。授权码通过前端传送,令牌则是储存在后端,而且所有与资源服务器的通信都在后端完成。这样的前后端分离,可以避免令牌泄漏。
1、授权码模式流程
第一步,A 网站提供一个链接,用户点击后就会跳转到 B 网站,授权用户数据给 A 网站使用。下面就是 A 网站跳转 B 网站的一个示意链接。
https://b.com/oauth/authorize?response_type=code&client_id=CLIENT\_ID&redirect_uri=CALLBACK\_URL&scope=read
上面 URL 中,response_type
参数表示要求返回授权码(code
),client_id
参数让 B 知道是谁在请求,redirect_uri
参数是 B 接受或拒绝请求后的跳转网址,scope
参数表示要求的授权范围(这里是只读)。
第二步,用户跳转后,B 网站会要求用户登录,然后询问是否同意给予 A 网站授权。用户表示同意,这时 B 网站就会跳回redirect_uri
参数指定的网址。跳转时,会传回一个授权码,就像下面这样。
https://a.com/callback?code=AUTHORIZATION_CODE
上面 URL 中,code
参数就是授权码。
第三步,A 网站拿到授权码以后,就可以在后端,向 B 网站请求令牌。
https://b.com/oauth/token?client_id=CLIENT\_ID&client_secret=CLIENT\_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=CALLBACK\_URL
上面 URL 中,client_id
参数和client_secret
参数用来让 B 确认 A 的身份(client_secret
参数是保密的,因此只能在后端发请求),grant_type
参数的值是AUTHORIZATION_CODE
,表示采用的授权方式是授权码,code
参数是上一步拿到的授权码,redirect_uri
参数是令牌颁发后的回调网址。
第四步,B 网站收到请求以后,就会颁发令牌。具体做法是向redirect_uri
指定的网址,发送一段 JSON 数据。
{ "access\_token":"ACCESS\_TOKEN","token\_type":"bearer","expires\_in":2592000,"refresh\_token":"REFRESH\_TOKEN","scope":"read","uid":100101,"info":{...} }
上面 JSON 数据中,access_token
字段就是令牌,A 网站在后端拿到了。
2、授权码模式实现代码
2.1 创建pom.xml
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0modelVersion><parent><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-parentartifactId><version>2.2.6.RELEASEversion><relativePath/> parent><groupId>com.dashigroupId><artifactId>springsecurity-oauthartifactId><version>0.0.1-SNAPSHOTversion><name>springsecurity-oauthname><description>Demo project for Spring Bootdescription><properties><java.version>1.8java.version><spring-cloud.version>Greenwich.SR5spring-cloud.version>properties><dependencies><dependency><groupId>org.springframework.cloudgroupId><artifactId>spring-cloud-starter-oauth2artifactId>dependency><dependency><groupId>org.springframework.cloudgroupId><artifactId>spring-cloud-starter-securityartifactId>dependency><dependency><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starterartifactId>dependency><dependency><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-webartifactId>dependency><dependency><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-testartifactId><scope>testscope>dependency>dependencies><build><plugins><plugin><groupId>org.springframework.bootgroupId><artifactId>spring-boot-maven-pluginartifactId>plugin>plugins>build><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloudgroupId><artifactId>spring-cloud-dependenciesartifactId><version>${spring-cloud.version}version><type>pomtype><scope>importscope>dependency>dependencies>dependencyManagement>project>
2.2 创建springsecurity配置文件
package com.dashi.springsecurityoauth.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/oauth/**","/login/**","/logout/**").permitAll().anyRequest().authenticated().and().formLogin().permitAll();}
}
2.3 创建UserService实现UserDetailService接口
package com.dashi.springsecurityoauth.model;import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;import java.util.Collection;
import java.util.List;public class User implements UserDetails {private String username;private String password;private List authorities;public User(String username, String password, List authorities) {this.username = username;this.password = password;this.authorities = authorities;}@Overridepublic Collection <span class="hljs-keyword"extends GrantedAuthority> getAuthorities() {return this.authorities;}@Overridepublic String getPassword() {return this.password;}@Overridepublic String getUsername() {return this.username;}@Overridepublic boolean isAccountNonExpired() {return true;}@Overridepublic boolean isAccountNonLocked() {return true;}@Overridepublic boolean isCredentialsNonExpired() {return true;}@Overridepublic boolean isEnabled() {return true;}
}
2.4 创建认证服务
package com.dashi.springsecurityoauth.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
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;@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("admin").secret(passwordEncoder.encode("654321")).accessTokenValiditySeconds(3600).redirectUris("http://www.baidu.com").scopes("all")//配置grant\_type,表示授权码授权.authorizedGrantTypes("authorization\_code");}
}
2.5 创建资源服务
package com.dashi.springsecurityoauth.config;import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().requestMatchers()//以/user开头的地址根据token访问资源.antMatchers("/user/**");}
}
2.6启动服务访问地址
http://localhost:8080/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all
2.7上一步连接跳转到输入用户名和地址
2.8 点击允许受访问的资源,跳转到授权网站(http://www.baidu.com),获取授权码
2.9 打开postman,填入下面内容获取token
2.10 通过token访问授保护的资源
参考文档:OAuth 2.0 的四种方式 - 阮一峰的网络日志 (ruanyifeng.com)
oauth2.0授权码模式详解相关推荐
- OAuth2.0授权码模式学习
OAuth2.0授权码模式学习 四种授权方式 1,授权码模式 2,简化模式 3,密码模式 4,客户端模式 授权码模式 四种授权模式中最完成,最严密的授权. (1)用户访问客户端,后者将前者导入认证服务 ...
- OAuth2.0授权协议与客户端授权码模式详解
本文来重点讲解下OAuth2.0授权协议与客户端授权码模式 文章目录 什么是OAuth协议 交互过程 客户端授权模式 授权码模式 简化模式 密码模式 客户端模式 接入公司内部系统 后台管理系统 前台业 ...
- OAuth2.0授权码模式原理与实战
OAuth2.0是目前比较流行的一种开源授权协议,可以用来授权第三方应用,允许在不将用户名和密码提供给第三方应用的情况下获取一定的用户资源,目前很多网站或APP基于微信或QQ的第三方登录方式都是基于O ...
- OAuth2.0授权码模式实战
OAuth2.0是目前比较流行的一种开源授权协议,可以用来授权第三方应用,允许在不将用户名和密码提供给第三方应用的情况下获取一定的用户资源,目前很多网站或APP基于微信或QQ的第三方登录方式都是基于O ...
- java 32位授权码_Java实现OAuth2.0授权码方式
Java实现OAuth2.0授权码方式 前面介绍了OAuth2.0和授权方式,可以参考以下文章: 今天就用Java来验证OAuth2.0授权方式的授权码式,我们Spring Cloud的OAuth来实 ...
- oauth2.0授权码_OAUTH 2.0授权码授予
oauth2.0授权码 OAuth 2.0提供了许多安全流程(或授权类型),以允许一个应用程序访问另一个应用程序中的用户数据. 在此博客中,我们将介绍OAuth 2.0授权:授权代码授权. 首先,有许 ...
- 如何获取QQ邮箱授权码——步骤详解
获取QQ邮箱授权码步骤详解 1.打开QQ邮箱,进入邮箱账户设置界面 下滑当前界面,显示到邮箱服务区域,选择自己需要开启的协议服务 或点击下方提示中的生成授权码 点击开启,显示验证密保弹窗,根据提示进行 ...
- OAuth2.0授权码认证流程介绍
Oauth2授权模式 Oauth2授权模式 Oauth2有以下授权模式: 1.授权码模式(Authorization Code) 2.隐式授权模式(Implicit) 3.密码模式(Resource ...
- oauth2使用授权码模式(authorization code)获取access_token
oauth2获取access_token的几种方式: 简化模式(implicit):在redirect_url中传递access_token,oauth客户端运行在浏览器中. 密码模式(passwor ...
最新文章
- Verlet-js JavaScript 物理引擎
- 039_Unicode对照表五
- 微服务实战(三):深入微服务架构的进程间通信
- Linux gdb调试器
- Web布局连载——两栏固定布局(五)
- input自适应_【正点原子FPGA连载】第十一章基于OV5640的自适应二值化实验-领航者ZYNQ之HLS 开发指南...
- SAP Marketing Cloud功能简述(四) : 线索和客户管理
- java xml 递归_Java递归遍历XML所有元素
- 对github的初步认识以及对软件技术基础课程的期待
- 快速入门python_一天快速入门 Python
- 人工智能风险分析技术研究进展
- js parseInt()和Number()区别
- 全球首发!计算机视觉Polygon Mesh Processing总结10——DEFORMATION
- [ NOI 2005 ] 聪聪与可可
- matlab的默认复数开方
- 浅谈如何根治慢性扁桃体炎-个人经验总结
- 计算机启动检测不到硬盘,电脑BIOS启动项找不到硬盘,该怎么办?
- Dim Temp%的意思
- 【公众号】JAVA微信公众号技术大佬文章精选
- 可能改变前端工程化未来的特性:ESM Loader Hooks
热门文章
- java 配置微信js sdk_Java微信公众平台开发(十一)--微信JSSDK中Config配置
- 基于SSM的游戏账号交易管理系统
- Linphone 实现局域网的组网呼叫 (官方的说法是Making an audio conference)
- 程序设计之HardCoding
- Conflux杨光:PoW和PoS的全面比较 | 碳话第一期
- mac未能正确推出移动硬盘而读取不了
- 计算机毕业设计Java快递代取(源码+mysql数据库+系统+lw文档)
- 前端视角下的转转客服通信过程
- 强烈推荐这款神器,一行命令将网页转PDF!
- 如何度量逻辑回归模型表现