当前位置:网站首页>JWT (SSO scheme) + three ways of identity authentication

JWT (SSO scheme) + three ways of identity authentication

2022-06-26 10:46:00 Slightly drunk CC

Statement :

  1. This blog resource comes from the Internet , Please let us know if there is any infringement ( Invasion and deletion ).
  2. This blog resource is for reference only , There is no profit for me !

One 、 Three ways of identity authentication

1.1 Single server mode


The general process is as follows :

  1. The user sends the user name and password to the server .
  2. After verifying the server , related data ( Such as user name , User roles, etc ) Will be saved in the current session (session) in .
  3. The server returns... To the user session_id,session Information will be written to the user's Cookie( be known as jSessionID Of Cookie).
  4. Each subsequent request from the user will be passed through the Cookie Remove from session_id To the server .
  5. Server received session_id And compare the data saved before , Confirm the identity of the user .

shortcoming :

  • Single point performance pressure , Can't expand .
  • In distributed architecture , need session Sharing scheme ,session There are performance bottlenecks in the shared solution .

session Sharing scheme :

session radio broadcast : Also called Session Synchronous or Session Copy , Let each in the cluster tomcat Of session Full synchronization , Not recommended .
redis Instead of session recommend , High performance , Usually Cookie+Redis Realization .

Session Sharing is an implementation of single sign on .

1.2 SSO( Single sign on )

   Single sign on (Single Sign On), The abbreviation is SSO. Its explanation is : In multiple application systems , Just log in once , You can access other trusted application systems .

   for example , The website has logged in to Taobao account , Tmall , Nailing and other Alibaba apps don't need to log in again .SSO The core meaning is : A login , Log in everywhere ; One cancellation , Write off everywhere . It's in multiple application systems , Users only need to log in once to access all mutual trust application systems , That is, users only need to remember a set of user names and passwords to log in to all authorized systems .

Common implementation schemes for single sign on include : Cookie+Redis, CASOAuth2( Third party login Authorization )、JWT etc. .

Simple case demonstration :

As shown in the figure below , The picture shows 3 A system ( Microservices ), Business A、 Business B、 And Certification Center . Business A、 Business B No login module . The certification center only has the certification module , There are no other business modules .

【 Picture from the Internet 】

SSO The general process is as follows :

  1. When business A、 Business B When you need to log in , Will jump to the certification center system .
  2. The authentication center obtains the user information from the user information database and verifies the user information , The certification center system completes login .
  3. Then store the user information in the cache ( for example redis).
  4. When users access the business A Or business B, Whether the user needs to log in or not , It will jump to the certification center system for user authentication , The authentication center determines whether there is user identity information in the cache .
  5. such , As long as one of the systems is logged in , Other applications will log in as well .

advantage : User identity information is managed independently , Better distributed management .
shortcoming : The access pressure of the certification center server is high .

1.3 Token

Refer to Blogger :chrisghb

1.3.1 token Verification process

   be based on Token Your authentication is No state Of , We don't store user information in the server . This concept solves many problems in storing information on the server .NoSession That means your program can add or remove machines as needed , Instead of worrying about whether users log in .

【 Picture from the Internet 】

be based on Token The process of authentication is as follows :

  1. The user sends the request through the user name and password .
  2. Server side program verification .
  3. The server-side program returns a signed token To the client .
  4. Client store token, And every time you visit API All carried Token To the server .
  5. Server side validation token, If the verification is successful, the request data will be returned , Error code will be returned if verification fails .

1.3.2 Use token Case demonstration of ( Sequence diagram )

This part of the picture is from chrisghb Blogger ( Simple books )

Sign in

Business request

Token Be overdue , Refresh Token

Refresh Token If expired , Require the user to log in and authenticate again .

1.3.3 token Advantages and disadvantages

advantage :

  • No state : token It's stateless ( The server side will not remember the user status ).
  • Security :token It's time limited , After a period of time, the user needs to revalidate .
  • Scalable :Tokens Can create programs that share permissions with other programs .
  • Multi platform cross domain :
  • Based on Standardization : Yours API Standardized... Can be used JSON Web Token (JWT).

shortcoming :

  • bandwidth ( Every time you request server resources, you must carry Token)
  • Cannot destroy on the server side

Two 、JWT

2.1 JWT token

JWT yes JSON Web Token Abbreviation , namely JSON Web token , It's a kind of Self contained token . JWT Official website

  JWT Mainly used in many web Server to achieve stateless distributed authentication ( Single sign on ),JWT There is a picture on the official website describing JWT The certification process ;

JWT The role of

  • JWT The most important function is to token The anti-counterfeiting function of information .

Be careful

  • Should not be in jwt Of payload Some store sensitive information , Because this part is the decryptable part of the client .
  • Well protected secret Private key , The private key is very important .
  • Use as much as possible https agreement .

2.2 JWT The composition of

JWT head Payload Verify the signature .

One JWT It's a very long string , Pass between characters "." The separator is divided into three substrings .

2.2.1 HEADER

JWT The first part It's a description JWT Metadata JSON object , Usually as follows .

{
    
  "alg": "HS256", // Algorithm of declaration encryption   Default direct use  HMAC SHA256( Written as  HS256)
  "typ": "JWT" 	  // Declaration type , Here is jwt
}

Last , Use Base64 URL The algorithm will JSON Object to string save .
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

2.2.2 PAYLOAD

Payload part , yes JWT The main content of , Also a JSON object , Contains data that needs to be passed .

{
    
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

The payload section consists of three sections :

  • A statement registered in the standard
  • Public statement
  • Private statement

A statement registered in the standard ( Recommended but not mandatory ) :

  • sub:jwt Target users ( The theme )
  • iss:jwt Issuer
  • aud: receive jwt On the side of
  • iat:jwt Issued on
  • exp:jwt The expiration time of , The expiration time must be greater than the issuing time
  • nbf: Define before what time , The jwt They're not available
  • jti:jwt Unique identity of , Mainly used as a one-off token, To avoid replay attacks

Public statement

Public statements can add any information , Generally add relevant information of users or other necessary information required by business . But it's not recommended to add sensitive information , Because this part can be decrypted on the client side .

Private statement

A private statement is a statement defined by both the provider and the consumer ( Customize ), It is generally not recommended to store sensitive information , because base64 It's symmetric decryption , It means that this part of information can be classified as clear text information ( Which can be viewed ).

{
    
  "sub": "1234567890",
  "iat": 1516239022,
  "name": "John Doe", # Private statement 
  "admin": true, # Private statement 
  "head_img": "helen.jpg" # Private statement 
}

Please note that :

  1. By default JWT Of PAYLOAD Part of it is unencrypted Of , Anyone can read it , So don't build private information fields to store confidential information , To prevent information from leaking .
  2. JSON Objects also use Base64 URL Algorithm converted to string save .( above payload The converted string is )
    eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJhZG1pbiI6dHJ1ZSwiaGVhZF9pbWciOiJoZWxlbi5qcGcifQ

2.2.3 VERIFY SIGNATURE

Verify the signature Part is to sign the data of the above two parts , Generate hash through specified algorithm , To ensure that data is not tampered with .

   First , You need to specify a password (secret)( The password is only saved in the server , And cannot be exposed to users ). then , Use the specified Signature Algorithm ( By default HMAC SHA256) Generate the signature according to the following procedure :

String encodedStr = base64UrlEncode(header) + '.' + base64UrlEncode(payload);
// according to  encodedStr  and  secret  and   Specified algorithm   Generate signature 
String signature = HMACSHA256(encodedStr, 'secret'); // HMACSHA256  Is the default signature algorithm 
  1. After calculating the signature hash ,JWT head , The three parts of the payload and signature hash are combined into a string , Each part uses "." Separate , It makes up the whole JWT object .

2.2.4 expand :Base64URL Algorithm

   As mentioned earlier ,JWT Both the header and payload serialization algorithms use Base64URL. This algorithm and common Base64 Similar algorithm , There is a slight difference .

   As a token JWT Can be placed in URL in ( for example api.example/?token=xxx). Base64 The three characters used in are "+","/“ and ”=", Because in URL Has a special meaning in , therefore Base64URL China has replaced them :"=“ Get rid of ,”+“ use ”-“ Replace ,”/“ use ”_" Replace , This is it. Base64URL Algorithm .

Be careful :base64 code , It's not encryption , It just turns the plaintext information into a string you don't know . But in fact, as long as you use some tools, you can make base64 The encoding is decoded into plaintext , therefore Not in JWT Put information about privacy in .

2.3 JWT Use

The client receives the JWT, Store it in Cookie or localStorage in .

thereafter , The client will bring... In the interaction with the server JWT.

Be careful :

  1. If you store it in Cookie in , You can send it automatically , But not across domains ( front end js Cannot get cross domain Cookie), So in general, I will JWT Put in HTTP Requested Header Authorization Field .
  2. When cross domain , Can also be JWT Placed in POST In the requested data body .

2.4 JWT Generation and analysis of (demo)

2.4.1 jwt Generate

// Expiration time , millisecond ,24 Hours 
private static long tokenExpiration = 24 * 60 * 60 * 1000;
// Secret key 
private static String tokenSignKey = "ccbx456jlqeukkcxmae";

@Test
public void testCreateToken() {
    
    JwtBuilder jwtBuilder = Jwts.builder();
    // head , load , Signature hash 
    String token = jwtBuilder.
            // head 
                    setHeaderParam("typ", "JWT") // Token type 
            .setHeaderParam("alg", "HS256") // Signature algorithm 
            // load , Default message 
            .setSubject("ccbx") // Token subject 
            .setIssuer("JackCC")// Issuer 
            .setAudience("hblg")// The receiver 
            .setIssuedAt(new Date())// The issuance of time 
            .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) // Expiration time 
            .setNotBefore(new Date(System.currentTimeMillis() + 20 * 1000)) //20 Available in seconds 
            .setId(UUID.randomUUID().toString())
            // load , Custom information 
            .claim("nickName", "JackMa")
            .claim("avatar", "1.jpg")
            // Signature hash 
            .signWith(SignatureAlgorithm.HS256, tokenSignKey)
            .compact(); // Convert to string 
    System.out.println(token);
}

Generated jwt object ( The following line breaks are manually performed by me , from . Start line feed )

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
eyJzdWIiOiJjY2J4IiwiaXNzIjoiSmFja0NDIiwiYXVkIjoiaGJsZyIsImlhdCI6MTY0MTU2NjA4OCwiZXhwIjoxNjQxNjUyNDg4LCJuYmYiOjE2NDE1NjYxMDgsImp0aSI6IjcyNjA1YzA0LTI3MDgtNDk4MC1iNzdlLTE0M2VkOThlMTEwNCIsIm5pY2tOYW1lIjoiSmFja01hIiwiYXZhdGFyIjoiMS5qcGcifQ.
eCygtpG_cEPP3lsU1sf3M3zmQQnGUM0CzKqKBwOh8Ds

2.4.2 jwt analysis

@Test
public void testGetInfo() {
    
    // To parse jwt
    String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJjY2J4IiwiaXNzIjoiSmFja0NDIiwiYXVkIjoiaGJsZyIsImlhdCI6MTY0MTU2NjA4OCwiZXhwIjoxNjQxNjUyNDg4LCJuYmYiOjE2NDE1NjYxMDgsImp0aSI6IjcyNjA1YzA0LTI3MDgtNDk4MC1iNzdlLTE0M2VkOThlMTEwNCIsIm5pY2tOYW1lIjoiSmFja01hIiwiYXZhdGFyIjoiMS5qcGcifQ.eCygtpG_cEPP3lsU1sf3M3zmQQnGUM0CzKqKBwOh8Ds";
    // obtain jwt Parser 
    JwtParser parser = Jwts.parser();
    Jws<Claims> claimsJws = parser.setSigningKey(tokenSignKey).parseClaimsJws(token);

    // analysis JWT head 
    JwsHeader header = claimsJws.getHeader();
    String algorithm = header.getAlgorithm();
    String type = header.getType();
    System.out.println(algorithm + "..." + type); //HS256...JWT
    System.out.println("********************************");

    // Parse payload 
    Claims claims = claimsJws.getBody();
    String subject = claims.getSubject();
    String issuer = claims.getIssuer();
    String audience = claims.getAudience();
    Date issuedAt = claims.getIssuedAt();
    Date expiration = claims.getExpiration();
    Date notBefore = claims.getNotBefore();
    String id = claims.getId();

    System.out.println(subject);    //ccbx
    System.out.println(issuer);     //JackCC
    System.out.println(audience);   //hblg
    System.out.println(issuedAt);   //Fri Jan 07 22:34:48 CST 2022
    System.out.println(expiration); //Sat Jan 08 22:34:48 CST 2022
    System.out.println(notBefore);  //Fri Jan 07 22:35:08 CST 2022
    System.out.println(id);         //72605c04-2708-4980-b77e-143ed98e1104
    String nickname = (String) claims.get("nickName");
    String avatar = (String) claims.get("avatar");

    System.out.println(" nickname :" + nickname);   // nickname :JackMa
    System.out.println(" Head portrait :" + avatar);     // Head portrait :1.jpg
    System.out.println("********************************");

    // Resolve signature hash 
    String signature = claimsJws.getSignature();
    System.out.println(signature);  //eCygtpG_cEPP3lsU1sf3M3zmQQnGUM0CzKqKBwOh8Ds
}

Analysis results :

I hope to correct my shortcomings , thank , Promotion and salary increase .

原网站

版权声明
本文为[Slightly drunk CC]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170528546856.html