当前位置:网站首页>OAuth 2.0 + JWT protect API security
OAuth 2.0 + JWT protect API security
2022-07-07 14:18:00 【Beth_ Chan】
Catalog
OAuth 2.0 Of 4 There are two ways of authorization
JWT What problems have been solved ?
Spring Cloud Security + OAuth 2.0 + JWT Application
Application access security basically revolves around authentication (Authentication) And authorization (Authorization) Two core concepts .
First, identify the user ( Authenticate users ), Confirm the identity and then determine whether the user has access to the specified resources , That is, identity authentication is the process of verifying identity , Authorization is the process of verifying whether you have access .
for instance , You need your ID card and ticket before you check in by plane : The ID card is to prove that Zhang San is indeed Zhang San , This is it. Authentication; The ticket is to prove that Zhang San did buy a ticket , You can get on the plane , This is it. Authorization.
The solution of mainstream certification is OAuth 2.0, Authorized solutions include Spring Security and Shiro. It has been used in different projects in the company .
OAuth 2.0 What is it?
OAuth 2.0 The standard is RFC 6749 file , It's an open 、 Secure user authentication protocol , Pass the authentication of user identity and issue token( token ), So that third-party applications can be used in a limited time 、 Use this token to access the specified resource .
OAuth 2.0 Agreement process
(1) After the user opens the client , Client requires authorization from user .
(2) User agrees to authorize client .
(3) The client uses the authorization obtained in the previous step , Request token from authentication server .
(4) The authentication server authenticates the client to , Agree to issue the token after confirmation .
(5) Client use token , Request resources from resource server .
(6) Resource server confirms that the token is correct , Agree to open resources to clients .
from OAuth 2.0 The authorization process shows , Authorization involves 4 Roles :
- client / Third-party applications (Client / Third-party Application): client / The third-party application sends a request to the resource server to access the protected resources on behalf of the resource owner .
- Resource owners (Resource Owner): A resource owner is a person who has the ability to authorize resources , Usually, that's what we call users .
- Authorization server (Authorization Server): It is commonly referred to as the authentication server , Provide different access tokens for client applications . The authorization server can be on the same server as the resource server , It can also be deployed independently .
- Resource server (Resource Server): The server where the resource is located , That is, resources protected by security authentication .
OAuth 2.0 Of 4 There are two ways of authorization
from OAuth 2.0 The authorization process shows , client ( Third-party applications ) You need to be authorized by the user (Authorization Grant) To get a token (Access Token).
OAuth 2.0 Defined 4 There are two ways of authorization : Authorization code mode (Authorization Code)、 Simplified mode (Implicit)、 Password mode (Resource Owner Password Credentials) And client mode (Client Credentials).
Be careful : Either way of Authorization , Before a third party application applies for a token , You have to go to the system first , Identify yourself , And then you get two IDS : client ID(client ID) And client key (client secret). This is to prevent the token from being abused , Third party applications that have not been filed , You won't get a token .
Voucher type (client credentials),
For command line applications without a front end , That is, request the token at the command line . The token given in this way , It's for third-party applications , Not for users , That is, it is possible for multiple users to share the same token .
First step ,A Apply to the command line B Request .grant_type
The parameter is equal to client_credentials
It means to use voucher type ,client_id
and client_secret
Used to make B confirm A The identity of the . The second step ,B After website verification , Return the token directly .
eg: https://xxx/auth-server/oauth/token?grant-type=client-credentials
Authorization code mode (Authorization Code)
Authorization code (authorization code) The way , It means that the third party application first applies for an authorization code , Then use the code to get the token .
This is the most common process , It's also the most secure , It works for those with back ends Web application , It works for those with back ends Web application . The authorization code is transmitted through the front end , Tokens are stored on the back end , And all communication with the resource server is done on the back end . This separation of the front and rear ends , Can avoid token leakage .
First step ,A Website provides a link , When the user clicks, he will jump to B Website , Authorized user data to A Site use . The following is A Website jump B A schematic link to the site .
https://b.com/oauth/authorize? response_type=code& client_id=CLIENT_ID& redirect_uri=CALLBACK_URL& scope=read
above URL in ,response_type
Parameter indicates that authorization code is required to be returned (code
),client_id
Parameter let B Know who's asking ,redirect_uri
Parameter is B Jump to the web address after accepting or rejecting the request ,scope
The parameter indicates the required authorization range ( This is read-only ).
The second step , After user jump ,B The website will require users to log in , Then ask if you agree to give A Website authorization . The user agreed , At this time B The website will jump back redirect_uri
Web address specified by parameter . When jumping , An authorization code will be returned
The third step ,A After the website gets the authorization code , On the back end , towards B Website request token .
https://b.com/oauth/token? client_id=CLIENT_ID& client_secret=CLIENT_SECRET& grant_type=authorization_code& code=AUTHORIZATION_CODE& redirect_uri=CALLBACK_URL
above URL in ,client_id
Parameters and client_secret
Parameters are used to B confirm A The identity of the (client_secret
Parameters are confidential , So requests can only be sent at the back end ),grant_type
The value of the parameter is AUTHORIZATION_CODE
, Indicates that the authorization method used is authorization code ,code
The parameter is the authorization code obtained in the previous step ,redirect_uri
Parameter is the callback URL after the token is issued .
Step four ,B After the website receives the request , The token will be issued . The specific approach is to redirect_uri
Designated web address , Send a paragraph JSON data .
{ "access_token": "ACCESS_TOKEN", "token_type": "bearer", "expires_in": 2592000, "refresh_token": "REFRESH_TOKEN", "scope": "read", "uid": 100101, "info": {...} }
above JSON In the data ,access_token
Field is token ,A The website is in the back end .
Other modes :
Simplified mode (Implicit)、 Password mode (Resource Owner Password Credentials) Rarely used , Here to ignore .
JWT(JSON Web Token)
JWT What is it? ?
JWT It's an open standard RFC7519, It represents a compact 、URL Safe 、 A statement that can be transmitted between network applications .JWT from header.payload.signature Three pieces of information constitute ,“.” Link to string . Online verification tools can be used (https://jwt.io) take token Ed / decode .
header The head describes the JWT The most basic information about , Such as type 、 Signature algorithm, etc :
(1) Token type typ:JWT
(2) encryption algorithm alg:JWT The default signature algorithm is HMAC SHA256, namely HS256.
payload load ( yes JWT The main body ) The valid information of the token is stored :
A statement registered in the standard (Registered Claims) It is to declare some standard attribute information in the token , Standard provisions are recommendations , Don't force .
Common attribute information is :
- iss: The issuer of the token ;
- sub: The user for which the token is intended ;
- aud: The party receiving the token ;
- iat: Token issuing time ;
- exp: Token expiration time ;
- nbf: Define the effective start time of the token , Not available before this time ;
- jti: Token unique identity , Mainly used as a one-time token , Avoid replay attacks .
signature:
Use the head and load Base 64 After the coding , Sign by the encryption method used , The signed results are placed in this section . for example :
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
Signature is used to verify whether the message has been changed during delivery , And for those signed with the private key Token It can also be verified JWT Is the sender of .secret It's stored on the server side ,JWT The signature generation of is also on the server side ,secret It's used to do JWT Issued and verified , therefore secret Is the server-side private key , In no scene should it be revealed .
JWT What problems have been solved ?
OAuth 2.0 The biggest pain point is not carrying user information , And the resource server cannot perform local authentication , Every access to a resource , All resource servers need to send requests to the authentication server , To verify Token The effectiveness of the 、 obtain Token Corresponding user information . Under distributed architecture , If there are a lot of related requests , The processing efficiency is very low , And the authentication server will become a central node , about SLA And processing performance .JWT It was born to solve these problems . ordinary OAuth 2.0 What is awarded is a string of random hash character string , It doesn 't make sense in itself , and JWT Format Token It has a specific meaning .
JWT Compared with the traditional Token Come on , Two pain points have been solved :
- Verify the signature ,Token The verification of can be done directly locally , There is no need to connect to the authentication server .
- stay Payload User related information can be defined in , This makes it easy to achieve Token Binding with user information .
At the time of certification , When users successfully log in with their credentials , One JSON Web Token Will be returned to . thereafter ,Token User credentials , Users want to access protected routes or resources , The user agent ( Usually a browser ) You should bring it with you JWT, Usually use Bearer schema Put it in Authorization header in , for example :
‘Authorization': 'Bearer ’ + token
Spring Cloud Security + OAuth 2.0 + JWT Application
spring-cloud-starter-oauth2 Dependency integration spring-cloud-starter-security、spring-security-oauth2、spring-security-jwt this 3 Dependencies .
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Edgware.SR3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencyManagement>
Configure authentication server :@EnableAuthorizationServer And extend AuthorizationServerConfigurerAdapter class
AuthorizationServerConfigurerAdapter The following are provided 3 Heavy duty configure Method :
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception{
// Used to configure the token endpoint (Token Endpoint) The security constraints of
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// Used to configure and initialize the client details service (ClientDetailService)
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// Used to configure authorization and Token Access endpoint and Token service , as well as Token Storage mode (eg:inMemory)
}
Spring Security OAuth 2.0 Expose two endpoints for checking token And access token:/oauth/check_token,/oauth/token_key, These endpoints are protected by default denyAll().
Configure resource servers :@EnableResourceServer And extend ResourceServerConfigurerAdapter class
@Override
protected void configure(HttpSecurity http) throws Exception{
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}
By default ,Token There will only be basic information such as user name , In practical applications, more information about users needs to be returned to the client , By customizing Token Enhancer to enrich Token Content .
in addition : If you use another way WebSecurityConfigurerAdapter, You can configure the BCryptPasswordEncoder Hash to save user passwords .
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin").roles("USER");
}
}
边栏推荐
- SAKT方法部分介绍
- Regular expression integer positive integer some basic expressions
- 高等数学---第八章多元函数微分学1
- The reason why data truncated for column 'xxx' at row 1 appears in the MySQL import file
- Excerpt from "misogyny: female disgust in Japan"
- Million data document access of course design
- Wired network IP address of VMware shared host
- Reverse non return to zero code, Manchester code and differential Manchester code of common digital signal coding
- Hangdian oj2092 integer solution
- ndk初学习(一)
猜你喜欢
Redis can only cache? Too out!
SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
libSGM的horizontal_path_aggregation程序解读
The delivery efficiency is increased by 52 times, and the operation efficiency is increased by 10 times. See the compilation of practical cases of financial cloud native technology (with download)
Assign a dynamic value to the background color of DataGrid through ivalueconverter
常用数字信号编码之反向不归零码码、曼彻斯特编码、差分曼彻斯特编码
Data flow diagram, data dictionary
PERT图(工程网络图)
数据流图,数据字典
The longest ascending subsequence model acwing 482 Chorus formation
随机推荐
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(二)
Is it safe to open an account online now? Which securities company should I choose to open an account online?
Selenium Library
手里的闲钱是炒股票还是买理财产品好?
Clickhouse (03) how to install and deploy Clickhouse
最长上升子序列模型 AcWing 1012. 友好城市
Battle Atlas: 12 scenarios detailing the requirements for container safety construction
How can the PC page call QQ for online chat?
The longest ascending subsequence model acwing 1012 Sister cities
Leetcode simple question sharing (20)
Regular expression integer positive integer some basic expressions
搜索框效果的实现【每日一题】
最长上升子序列模型 AcWing 1014. 登山
Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
AI talent cultivation new ideas, this live broadcast has what you care about
杭电oj2092 整数解
常用數字信號編碼之反向不歸零碼碼、曼徹斯特編碼、差分曼徹斯特編碼
GVIM [III] [u vimrc configuration]
PERT图(工程网络图)
股票开户首选,炒股交易开户佣金最低网上开户安全吗