The previous article introduced OAuth2.0 and how to use it. Net to achieve oAuth-based authentication, this article is a supplement to the previous article, mainly introduces the relationship and difference between OAuth, Jwt and OpenID Connect.

The main contents of this article are: ● Introduction to Jwt ● Jwt implementation of.NET ● OAuth and Jwt ● OAuth Bearer Token implementation in.NET ● OAuth and OpenID Connect

Note: this chapter content source code download: files.cnblogs.com/files/selim…

Jwt profile

Jwt(Json Web Token) is a jSON-based standard for secure information transfer. Jwt has the following characteristics: Since Jwt is intended for the Web, you need to keep the data as small as possible to carry it in urls, Post parameters, or Http headers, and because the data is small, it also increases the speed of data transmission. ● Self-contained: The playload section of Jwt contains all the information that should be included, especially when Jwt is used for authentication. Playload contains the user’s necessary identity information (note: it should not contain sensitive information), so that there is no need to query the user’s information in the database during authentication. ● Trust: Jwt is with digital signature, you can know whether Jwt is tampered in the transmission process, to ensure the integrity of the data, available signature algorithm RS256(RSA+SHA-256), HS256(HMAC+SHA-256), etc.

Jwt has two uses. One is for data interaction, because Jwt is signed to ensure data integrity. The other is to carry user information for authentication.

The Jwt contains three parts: ● Header: Contains the signature algorithm and the token type (default: Jwt). Such as:

  

Note: ALG and TYP are abbreviations designed to reduce the size of JWT.

Low Playload: Contains the information carried by Jwt. Playload contains three definitions of claims, which are standard respectively, such as ISS (Issuer, Jwt publisher), SUB (Subject, user represented by Jwt), AUD (audience, Recipients of Jwt), exp(expiration time), and some common conventions such as www.iana.org/assignments… And private custom ones, which are used to store specific information. The Playload structure is as follows:

  

● Signature: base64Url encoded Signature that contains the Header and Playload. The calculation process is as follows:

  

Finally, the three parts are encoded in Base64Url with the symbol “. Here is an example of a complete Jwt:

  

Note: the data in Jwt is transparent, since anyone who gets the data can see the content in the form of Base64Url unencoding. The signature only guarantees that the content will not be modified, so sensitive data cannot be included in Jwt. The above examples are from jwt. IO/Introductio… 六四屠杀

.NET Jwt implementation

Jwt is a standard and you can see implementations of Jwt in many different languages on jwt. IO /, while. Net is one of the implementation of the System. IdentityModel. Tokens. Jwt component, the component is implemented by Microsoft, it has two important types are: note: As the name (IdentityModel) indicates, Microsoft’s implementation is primarily for authentication. If you use Jwt for other purposes than authentication, you can choose another component or custom implementation. Low JwtSecurityToken: This type is an encapsulation of Jwt. In addition to the three elements of Jwt (Header, Playload, Signature), it also extends some important attributes such as Subject, Iusser, Audiences, validity period, Signature algorithm, Signature key and so on. Here is part of the JwtSecurityToken definition:

  

Low JwtSecurityTokenHandler: This object is used to perform operations on Jwt, such as Jwt creation, validation (including validation by publisher, receiver, signature, etc.), Jwt serialization and deserialization (converting from string form to object form).

  

Request and Jwt

OAuth is an authorization protocol and Jwt is an information security transmission standard. It seems that there is no relationship between them, but in fact, OAuth’s Access Token has a way of implementation is Jwt. Why use Jwt as OAuth Access Token? First take a look at the Access Token generated in the previous article:

  

It is an encrypted string, the string contains information about the user, but the string can only be used Microsoft. Owin. Security. Request component application decryption (not including the realization of the reference source), and to ensure the encryption keys are the same. However, OAuth is often used in distributed scenarios, and even different applications and services are written in different languages. In this case, the implementation of the above Token cannot meet the requirements. Therefore, Jwt Bearer tokens need to be used to solve the Token recognition problems in different applications.

OAuth authentication is implemented using Jwt Bearer Token in.NET

Mentioned in the previous article in the Microsoft. Owin. Security. Request the production of components in the Access Token is actually for a AuthenticationTicket object serialized and encrypted string, The authentication of Access Token is the process of decrypting and deserializing the encrypted string to obtain the AuthenticationTicket object. For Access Token from Microsoft. Owin. Security. Request component is implemented or Jwt, or even a custom format, its core is how the user information is contained in a string Token, And you can retrieve the correct user information from this string token. For this process in. Net’s Owin authentication solution abstracts this as an ISecureDataFormat interface, where the generic TData type for authentication is AuthenticationTicket. The ISecureDataFormat interface is defined below. Its two methods are used to convert string encryption tokens to user information objects. See ASP.NET without magic — encryption and decryption of ASP.NET Identity

  

In the previous article also gives the Microsoft. Owin. Security. Request component, the default is TicketDataFormat to decrypt the Access Token and object, the object is in fact an implementation of a ISecureDataFormat interface types, Used to complete the serialization and encryption and decryption of data objects through the data protector, can refer to “ASP.NET no magic — ASP.NET Identity encryption and decryption” :

  

One way to think about it is that. Net to implement OAuth authentication based on Jwt Bearer Token, Need only in Microsoft. Owin. Security. Request components on the basis of a custom ISecureDataFormat < AuthenticationTicket > type.

A description of the main properties of Jwt

● Issuer: the Issuer of the Token. The Jwt contains information about the tokens that will be authenticated. The Issuer is the authentication server itself. ● A Token generated by the publisher is generated by the Audience. The whole authentication system is distributed and contains multiple applications centered on the publisher. In order to ensure data security, one Token should only be valid for one application, so the Audience should be verified during Jwt verification. ● Subject: Subject, used in authentication to store user information, such as the user name.

Their relationship is shown below:

  

User represents Subject. There is a concept of Client in OAuth, and the Client of OAuth is equivalent to Audience. Now that you’ve implemented Client management, add a digital signature key to each Client, which is a Base64 encoded string in a 32-bit byte array. In addition, HMAC algorithm is used to complete the summary calculation of tokens.

  

Implement a JWt-based ISecureDataFormat<AuthenticationTicket>

Here’s how to implement ISecureDataFormat: 1. Via Nuget install Microsoft. Owin. Security. Jwt components: note: Microsoft implements a used to resolve Jwt Bearer Token of components, but the component only Unprotect method, using this component development can reduce some workload.

  

2. Understand Microsoft. Owin. Security. Jwt JwtFormat type: Microsoft. Owin. Security. Jwt implements a JwtFormat object, the object is realized the need of ISecureDataFormat interface:

  

But the object does not implement the Protect method:

  

The main work of its UnProtect method is as follows:

  

Low for the publisher and the signature of the Token and expiration time for validation (note: verify operation is made up of the System. IdentityModel. Tokens. Jwt JwtSecurityTokenHandler type of component). ● Obtain the user information contained in the Token after the authentication is successful.

3. Implement Jwt Protect method:

  

Complete code:

1 public class MyJwtFormat : ISecureDataFormat<AuthenticationTicket> 2 {3 // Used to obtain Audience information from AuthenticationTicket 4 private const string AudiencePropertyKey = "aud"; 5 6 private readonly string _issuer = string.Empty; 7 public MyJwtFormat(string issuer) 9 {10 _issuer = issuer; 8 public MyJwtFormat(string issuer) 9 {10 _issuer = issuer; 11 } 12 13 public string Protect(AuthenticationTicket data) 14 { 15 if (data == null) 16 { 17 throw new ArgumentNullException("data"); 18} / / get the name and the information on 19 20 string audienceId = data. The Properties. The Dictionary. Either ContainsKey (AudiencePropertyKey)? 21 data.Properties.Dictionary[AudiencePropertyKey] : null; 22 if (string.IsNullOrWhiteSpace(audienceId)) throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience"); 23 var audience = ClientRepository.Clients.Where(c => c.Id == audienceId).FirstOrDefault(); 24 if (audience == null) throw new InvalidOperationException("Audience invalid."); 25 // Create the SigningCredentials for digital signatures based on the key, The object using var keyByteArray = 26 in JwtSecurityToken TextEncodings. Base64Url. Decode (on Secret); 27 var signingKey = new InMemorySymmetricSecurityKey(keyByteArray); 28 var signingCredentials = new SigningCredentials(signingKey, 29 SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); 30 / / obtain release date and expiration date 31 var issued = data. The Properties. IssuedUtc; 32 var expires = data.Properties.ExpiresUtc; 34 var Token = new JwtSecurityToken(_issuer, 35 audienceId, 36 Data.identity. Claims, 37 issued.Value.UtcDateTime, 38 expires.Value.UtcDateTime, 39 signingCredentials); 41 var Handler = new JwtSecurityTokenHandler(); 42 var jwt = handler.WriteToken(token); 43 return jwt; 44 } 45 46 public AuthenticationTicket Unprotect(string protectedText) 47 { 48 throw new NotImplementedException(); 49}} 50Copy the code

View Code

The above code does the following: ● Get the Audience information from AuthenticationTicket. Net object used to store user information, which carries additional information such as the validity period of authentication in addition to user information, such as user name and user Claims, as shown in the figure below. You can create an AuthenticationTicket in either of two ways. During login, the user information is obtained from the database after the login information is correct and the authentication information, such as the validity period, is obtained from the configuration or default. The other is to obtain identity Token through deserialization. The Protect method here is actually the method that serializes the Token, so the AuthenticationTicket it gets is created using the first general method.)

  

● Create a SignatureCredentials object for digital signature that represents the algorithm used for digital signature and its key solely because it is required by the JwtSecurityToken object to complete Token creation. ● Create a Token using the JwtSecurityToken object. The creation of the Token requires information about the issuer, audience, user Claims, publication time, validity period, and digital signature algorithms and keys. ● Serialize the Token via the JwtSecurityTokenHandler.

3. Add the Audience information in AuthenticationTicket. It is mentioned above that Audience information is required when creating Token, and Token is created through AuthenticationTicket. Therefore, Audience information needs to be added when creating AuthenticationTicket. In addition, the above mentioned two creation methods of AuthenticationTicket are also mentioned. The method used here is created during “login”, while the “login” of OAuth is realized through different types of “authorization”, so the Audience information should be added. Just add it to the authorization code of the corresponding mode (for example, copy the code of other methods based on user name and password) :

  

4. Add JwtBearerAuthentication middleware for Token parsing to Audience(Client) :

  

In other words, the Client contains limited resources. When accessing these resources, it needs to resolve the Token to complete the authentication. However, audiences or clients are relatively independent, so it should limit accessible audiences and have its own encryption key, and even verify the publisher to confirm the security of token. (Note: in this example, the authentication server and Client are included in the same application, which can be separated in practice, so that a simple single sign-on system).

5. Run the program

  

The Token can be used to access restricted resources:

  

Here is the result of decoding Token Base64, and you can see the information contained in Jwt:

  

Test1 cannot access the resource protected by test1 if you use the Token obtained by test2:

  

Authentication failed, redirect to login page:

  

Request with OpenID Connect

OAuth is an authorization protocol, but there is a contradiction between authentication and authorization. As mentioned in the previous article, the purpose of authentication is to know who “you” are. Authorization determines whether “you” have access to a resource. But everything about OAuth since the last article is about authentication. Authorization agreements are used for authentication, so they are contradictory. OpenID Connect is an authentication protocol supplemented and expanded on the basis of OAuth protocol to make up for the defects of OAuth protocol. It includes new advanced features such as discovery services, dynamic registration, Session management, and logout mechanisms. OAuth is used for authentication only because OAuth is relatively simple and suitable for small projects. It has nothing to do with whether OAuth is an authorization protocol or an authentication protocol. It is concerned with whether OAuth can meet the requirements. Including app. UseOAuthBearerAuthentication method name is Authentication instead of Authorization, by adding request Bearer Authentication middleware to implement Authentication. OpenID Connect is more suitable for large projects and won’t be covered here.

For more information about OAuth and OpenID Connect, see BlackHeart’s blog. Thank you blackheart for your advice. ^_^

summary

This chapter introduces Jwt and Jwt in. Net implementation, and introduced in. Net how to use Jwt Token to implement OAuth based authentication. The main purpose of using Jwt Token is to solve the Token recognition problem of different applications. Finally, the difference between OAuth and OpenID Connect is simply explained. The key point of their choice lies in the demand. OAuth can meet the demand for small applications, and OpenID Connect is very complex. Open source components such as IdentityServer can also be considered if needed.

  

Authentication related content for now, about. Net security related content can be found in the following blog, very comprehensive covers of authentication and. Net encryption and decryption content: dotnetcodr.com/security-an…

Reference:

Dzone.com/articles/wh… Stackoverflow.com/questions/3… Openid.net/specs/draft… Tools.ietf.org/html/rfc752… Auth0.com/learn/json-… Stackoverflow.com/questions/3… Stackoverflow.com/questions/1… www.c-sharpcorner.com/UploadFile/… Security.stackexchange.com/questions/9… www.cnblogs.com/linianhui/a…

This paper links: www.cnblogs.com/selimsong/p…

ASP.NET has no magic — directories