当前位置:网站首页>After having a meal with trump, I wrote this article
After having a meal with trump, I wrote this article
2022-07-25 12:13:00 【JackLi0812】
GitHub OAuth2.0 Sign in SpringBoot Principle and practice
List of articles
1. Preface
Recently, I had two wonderful dreams and shared happiness with you .
Dream 1: In my first dream, I dreamed that I was withtrumphaving dinner , Then telltrumpHe needs to learn from China , Take epidemic prevention as the first task , Then he didn't listen , He left angrily , Then I will call on everyone to oppose him , Later, more and more people opposed it ,<< Friends >>MediumChandler( I don't know why it's him ) Also joined my camp ,trumpI can't sit down , Just put it in front of meChandlerI threw it down from the roof of a 100 story building (Sorry), Dead old miserable (Sorry too…)…
Dream2: The second dream was made on Friday night this week , Dream of going back to my hometown , Then transfer the subway to the bus for an hour and a half , After getting off the bus, I have to transfer to the city bus for thirty or forty minutes to get home , Feel so far away , I don't know
<< naruto -- Fast wind >>Inside, the fourth forbearance world warCompendiumThe upper line was too far away, so he used the space-time Ninja to transmit materials to the front line of the fourth World War , So , I was thinking. , Can you expand Java Of IO flow , Will oneselfWriteBack home ( This dream , Very speechless )
These two dreams make me happy every time I think of them , I hope you too … Ha ha ha ha … Okay , Get down to business
just as As mentioned above , User registration is a very disgusting thing for users , therefore , quick , Convenient user registration process can better retain users , therefore , jfoa: https://github.com/JavaFamilyClub/jfoa Introduced OAuth 2.0 authentication , At present, we support
GitHubAuthentication realizes registration and login . As promised , Talk to you today OAuth 2.0 The implementation and principle of .
OAuth 2.0yes RFC 6749: https://tools.ietf.org/html/rfc6749 Proposed an authorization framework model ,RFC 6749YesOAuth 2.0The introduction is as follows :
The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf. This specification replaces and obsoletes the OAuth 1.0 protocol described inRFC 5849.OAuth 2.0The authorization framework supports third-party applications to obtain access to HTTP Limited access to services , Coordinate approval interactions to represent resource owners between resource owners and HTTP Between services , Or by allowing third-party applications to gain access on their behalf . This specification replaces and eliminates RFC 5849: https://tools.ietf.org/html/rfc5849 Described inOAuth 1.0agreement .
2. OAuth role
OAuth Four roles are defined :
- Resource owner
An entity that can grant access to protected resources , When the resource owner is a person , It's called the end user .
- Resource server
The server hosting the protected resource , Be able to accept and respond to requests from protected resources using access tokens .
- Customer (client)
Applications that make requests for protected resources on behalf of resource owners and their authorizations .
- Authorization server
After successfully authenticating the resource owner and obtaining authorization , The server issues an access token to the client .
A basic access process is as follows :

(A) The client requests authorization from the resource owner . The authorization request can be sent directly to the resource owner , Or it is better to use the authorization server as an intermediary indirectly .
(B) The client receives the license , The authorization license is the credential that indicates the authorization of the resource owner , Use
OAuth 2.0One of the four authorization types provided or the extended authorization type represents . The type of authorization depends on the client of the method used , Request authorization and authorize the server through supported types .(C) The client requests an access token by authenticating with the authorization server and providing authorization permission .
(D) The authorization server authenticates the client and verifies the authorization license , If effective , Issue an access token .
(E) Client requests protected resources from resource server , And authenticate by providing an access token .
(F) Resource server authentication access token , If effective , Then service the request .
3. OAuth The license
Licensing is the client's use of resources ( Access to its protected resources ) To obtain the credentials of the access token , The specification defines four authorization methods
- Authorization code
- Implicit
- Resource owner password
- Client credentials
Besides , OAuth 2.0 It also provides user-defined extensible mechanisms of other types .
3.1 Authorization code
By using the authorization server as an intermediary between the client and the resource owner , You can get the authorization code . The client does not request authorization directly from the resource owner , Instead, the resource owner is directed to the authorization server ( adopt RFC2616: https://tools.ietf.org/html/rfc2616 User agents defined in ), The latter guides the resource owner back to the client together with the authorization code .
Before using the authorization code to guide the resource owner back to the client , The authorization server authenticates the resource owner and obtains authorization . Because the resource owner only authenticates through the authorization server , Therefore, the credentials of the resource owner will never be shared with the client .
Authorization code provides some important security benefits , For example, the ability to authenticate clients , And the process of transferring the access token directly to the client , Instead of passing it on to the user agent of the resource owner and possibly exposing it to others , Including resource owners .
3.2 Implicit license
Implicit authorization is a simplified authorization code process , This process is aimed at using JavaScript Such scripting languages are optimized for the client implemented in the browser . In an implicit process , Do not issue authorization codes to clients , Instead, the access token is granted directly to the client ( As a result of the authorization of the resource owner ). The grant type is implicit , Because no intermediate certificate was issued ( For example, the authorization code used to obtain the access token in the future ).
When issuing an access token in the implicit grant process , The authorization server will not authenticate the client . In some cases , You can use redirection to pass the access token to the client URI Verify client identity . Access tokens can expose access rights to resource owners or other user agent applications with resource owners .
Implicit grant improves some clients ( for example , Implement as the client of the application in the browser ) Responsiveness and efficiency , Because it reduces the number of round trips required to obtain an access token . however , This convenience should be weighed against the security risks caused by the use of implicit authorization , Especially when the authorization code authorization type is available .
3.3 Resource owner password
The password of the resource owner ( User name and password ) It can be directly used as an authorization to obtain an access token . Only when there is high trust between the resource owner and the client ( for example , The client is part of the device operating system or highly privileged Application ), And other authorization types are not available ( For example, authorization code ), You should use this licensing method .
Even if this grant type requires the client to directly access the resource owner credentials , Resource owner credentials are also used for individual requests , And exchange access tokens . This grant type can eliminate the need for clients to store resource owner credentials for future use by exchanging credentials with long-term access tokens or refresh tokens .
3.4 Customer voucher
When the authorization scope is limited to the protected resources under the control of the client or the protected resources previously arranged with the authorization server , Client credentials can be ( Or other forms of client authentication ) As a license . Usually , When the client represents itself ( The client is also the resource owner ) Action or access to protected resources based on authorization requests previously scheduled with the authorization server , Client credentials will be used as authorization licenses .
There are many concepts and details , If you are interested, you can refer to RFC 6749: https://tools.ietf.org/html/rfc6749 .
4. Practical drill
Here it is... Here it is , Here comes the play , Today is the day jfoa: https://github.com/JavaFamilyClub/jfoa To do it
Github OAuth2.0 Sign in SpringBoot applicationThe drill of , becausejfoaSelf supportGithubregister / After logging in and going online , It has experienced the test of real server and production environment for some time .

jfoaUse authorization code Github Certificate authority . The basic process is as follows :

4.1 Application registration
An application requires OAuth to grant authorization , You must register at the other party's website first , Let the other party know who is requesting . therefore , You have to go first GitHub Check in .
- Get into GitHub Setting

- Enter developer settings

- Get into
OAuth Apps, establish App

There are already two in the figure above App, One is
jfoaProduction environment App, One isjfoaDevelopment environment App(jfoaAdopt the development mode of separating production environment and development environment , otherwise , Development debugging or testing will have an impact on the production environment , For example, the development environment registers users , Deleting users will affect the development environment and generate dirty data )
- Fill in App Information (
Tips : Local localhost Applications are also supported , Because it's just a callback address), The following is the development modejfoaOf App To configure

- see client_id And generate client_secret

4.2 Available in browser through GitHub Login interface

As shown in the figure above ,
jfoaFor security reasons , takeclient_idandclient_secretAnd other important information are stored in Server And encrypted , So the UI Not directly request Github to grant authorization , But first visitjfoaThe server of gets parameter information , Then redirect .
@GetMapping("/public/oauth/github/auth")
public String auth() {
String authorizeUrl = githubProvider.getAuthorizeUrl();
return "redirect:" + authorizeUrl;
}
also
jfoaStore the ciphertext in the environment variable , And inbuild.gradleReference environment variables in . If you refer tojfoaProject words , Need to replacejfoa/runner/src/main/resources/application.ymlMediumclient_idandclient_secretFor your own information

Final , Click on GitHub The login button will redirect to :
https://github.com/login/oauth/authorize?scope=user:emailresponse_type=code&redirect_uri=http://localhost/public/oauth/github/callback&state=1&client_id=XXX
4.3 Jump to GitHub To authorize
You will enter through the redirection in the previous step GitHub The authorization server of , to grant authorization GitHub You need to log in first GitHub

After login , First visit OAuth App when GitHub Will need you to OAuth App To authorize . This page will list OAuth App Basic information and OAuth App Requested resources ( This is it. OAuth 2.0 Resource access restrictions )

4.4 Return authorization code
When you are right OAuth App After authorization , Github The authorization server will carry the authorization code and status information to redirect to your request GitHub Carried during certification
redirect_uriDesignated address . namely :http://localhost/public/oauth/github/callback?code=YYY&state=1jfoaYou will visit the following controller:
@GetMapping("/public/oauth/github/callback")
public String callback(@RequestParam("code") String code,
@RequestParam("state") String state)
{
AccessTokenResponse accessTokenResponse
= githubProvider.queryAccessToken(code, state);
authentication(accessTokenResponse);
return "redirect:/";
}
ad locum , adopt
RestTemplate+Apache Http Clientrequest GitHub Authorization code , The request address is as follows :
https://github.com/login/oauth/access_token?client_id=XXX&client_secret=***&code=YYY&redirect_uri=http://localhost/public/oauth/github/callbackstate=1
4.5 adopt access_token Access resources
Get access_token Then you can access the resources authorized by the user , such as
jfoaCurrently, the user's account will be requested , user name , company , Introduction and email information .
Through the following request :
https://api.github.com/user?access_token=*****
access_token It needs to be transmitted with the information of the request header , above URL It only states that you need to carry this information
default HttpHeaders queryResourceHeader(AccessTokenResponse token) {
HttpHeaders headers = new HttpHeaders();
headers.set(authorizationParamName(),
token.getToken_type()
+ " " + token.getAccess_token());
return headers;
}
Postman In the following configuration :

4.6 Authenticate users according to the obtained user information and business
jfoaWill use “GitHub:” + user GitHub Account is used as user account to register and login users . You can change flexibly according to your business needs .
thus , OAuth 2.0 The basic theory and practice of , On the whole OAuth2.0 have a lucid brain , Specific goals , But if you are in contact for the first time, you still need to practice it yourself , Shuai Shuai also encountered some problems in practice and has a deep memory , I'll share it with you later , Let's practice by ourselves .

边栏推荐
- 【GCN-RS】Are Graph Augmentations Necessary? Simple Graph Contrastive Learning for RS (SIGIR‘22)
- 'C:\xampp\php\ext\php_zip.dll' - %1 不是有效的 Win32 应用程序 解决
- aaaaaaaaaaA heH heH nuN
- Brpc source code analysis (VI) -- detailed explanation of basic socket
- Power BI----这几个技能让报表更具“逼格“
- GPT plus money (OpenAI CLIP,DALL-E)
- LeetCode第303场周赛(20220724)
- How to solve the problem of the error reported by the Flink SQL client when connecting to MySQL?
- Application and innovation of low code technology in logistics management
- Sword finger offer 22. the penultimate node in the linked list
猜你喜欢

嵌套事务 UnexpectedRollbackException 分析与事务传播策略

记录一次线上死锁的定位分析

和特朗普吃了顿饭后写下了这篇文章
![[multimodal] transferrec: learning transferable recommendation from texture of modality feedback arXiv '22](/img/02/5f24b4af44f2f9933ce0f031d69a19.png)
[multimodal] transferrec: learning transferable recommendation from texture of modality feedback arXiv '22

【RS采样】A Gain-Tuning Dynamic Negative Sampler for Recommendation (WWW 2022)

【6篇文章串讲ScalableGNN】围绕WWW 2022 best paper《PaSca》

【Debias】Model-Agnostic Counterfactual Reasoning for Eliminating Popularity Bias in RS(KDD‘21)

Pycharm connects to the remote server SSH -u reports an error: no such file or directory

【对比学习】Understanding the Behaviour of Contrastive Loss (CVPR‘21)

对比学习的应用(LCGNN,VideoMoCo,GraphCL,XMC-GAN)
随机推荐
JS interview question: handwriting throttle function
【Debias】Model-Agnostic Counterfactual Reasoning for Eliminating Popularity Bias in RS(KDD‘21)
嵌套事务 UnexpectedRollbackException 分析与事务传播策略
马斯克的“灵魂永生”:一半炒作,一半忽悠
氢能创业大赛 | 国家能源局科技司副司长刘亚芳:构建高质量创新体系是我国氢能产业发展的核心
Zero shot image retrieval (zero sample cross modal retrieval)
Hydrogen entrepreneurship competition | Liu Yafang, deputy director of the science and Technology Department of the National Energy Administration: building a high-quality innovation system is the cor
I advise those students who have just joined the work: if you want to enter the big factory, you must master these concurrent programming knowledge! Complete learning route!! (recommended Collection)
Transformer variants (spark transformer, longformer, switch transformer)
What is the difference between session and cookie?? Xiaobai came to tell you
R语言组间均值是否相同的成对比较:使用pairwise.t.test函数执行多个分组数据均值的两两成对假设检验
【高并发】我用10张图总结出了这份并发编程最佳学习路线!!(建议收藏)
【AI4Code】《IntelliCode Compose: Code Generation using Transformer》 ESEC/FSE 2020
【GCN-RS】Are Graph Augmentations Necessary? Simple Graph Contrastive Learning for RS (SIGIR‘22)
[dark horse morning post] eBay announced its shutdown after 23 years of operation; Wei Lai throws an olive branch to Volkswagen CEO; Huawei's talented youth once gave up their annual salary of 3.6 mil
[untitled]
Brpc source code analysis (VI) -- detailed explanation of basic socket
【RS采样】A Gain-Tuning Dynamic Negative Sampler for Recommendation (WWW 2022)
Atomic 原子类
Week303 of leetcode (20220724)