当前位置:网站首页>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 What is it?

OAuth 2.0 Agreement process

OAuth 2.0 Of 4 There are two ways of authorization

JWT(JSON Web Token)

JWT What is it? ?

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");
  }
}

原网站

版权声明
本文为[Beth_ Chan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071216006334.html