ASP. NET has no magic-ASP. NET OAuth, jwt, OpenID Connect, oauthopenid
The previous article introduced OAuth2.0 and how to use it. net to implement OAuth-based identity authentication. This article is a supplement to the previous article. It mainly introduces the relationship and difference between OAuth, Jwt, and OpenID Connect.
The main contents of this article include:
● Jwt Introduction
●. Net Jwt implementation
● OAuth and Jwt
● Using Jwt Bearer Token in. Net for OAuth
● OAuth and OpenID Connect
Note: This chapter content source code download: https://files.cnblogs.com/files/selimsong/OAuth2Demo_jwt.zip
Introduction to Jwt
Jwt (Json Web Token) is a secure information transmission standard based on Json. Jwt has the following features:
● Compact: Jwt is prepared for the Web, so it is necessary to make the data as small as possible to carry Jwt in the Url, Post parameter, or Http Header, and because the data is small, therefore, the data transmission speed is also increased.
● Self-contained: The playload part 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: sensitive information should not be included). In this way, you do not need to query user information in the database during authentication.
● Trusted: Jwt is digital signature, it can know whether Jwt is tampered during transmission, ensure data is complete, available signature algorithm RS256 (RSA + SHA-256), HS256 (HMAC + SHA-256) and so on.
Jwt has two purposes: one is used for data interaction, because Jwt is signed to ensure data integrity. In addition, it is used to carry user information for identity authentication.
Jwt consists of three parts:
● Header: contains the signature algorithm and Token type (JWT by default ). For example:
Note: Both alg and typ are abbreviations to reduce the size of jwt.
● Playload: contains the information content carried by Jwt. Playload includes three types of Claim (Declaration) definitions, which are standard, such as iss (issuer, Jwt issuer) sub (subject, user represented by Jwt), aud (receiver of Jwt), exp (expiration time of Jwt), and some public conventions such: bytes.
The Playload structure is as follows:
● Signature: contains the Signature result of the Header and Playload base64Url encoded. The calculation process is as follows:
The three parts are encoded using Base64Url and separated by the symbol ".". The following is an example of a complete Jwt:
Note: The data in Jwt is transparent. If anyone obtains the data, they can see the content in the form of Base64Url anti-encoding. The signature only ensures that the content is not modified by expires, so the Jwt cannot contain sensitive data. The above examples are from https://jwt.io/introduction/
. Net Jwt implementation
Jwt is a standard:
Note: From the names (IdentityModel), we can see that Microsoft's implementation is mainly used for identity authentication. If the purpose of Jwt is not identity authentication, you can select other components or custom implementation.
● JwtSecurityToken: This type is a Jwt encapsulation. It contains three elements (Header, Playload, and Signature) of Jwt, it also expands important attributes such as Subject, Iusser, Audiences, validity period, signature algorithm, and signature key.
Is the partial definition of JwtSecurityToken:
● JwtSecurityTokenHandler: This object is used to operate Jwt, such as Jwt creation and verification (including publisher, receiver, signature, and other verification) jwt serialization and deserialization (Conversion between string form and object form)
Is the partial definition of JwtSecurityTokenHandler:
OAuth and Jwt
The former is an authorization protocol and the latter is an information security transmission standard. It seems that there is no relationship between them, but in fact, there is a way to implement OAuth Access Token is Jwt.
Why use Jwt as the Access Token of OAuth? First, let's take a look at the Access Token generated in the previous article:
It is an encrypted string that contains user-related information. However, this string can only be used by Microsoft. owin. security. the application of the OAuth component decrypts data (excluding the implementation of the source code) and ensures that the encryption and decryption keys are the same. However, OAuth is often used in some distributed scenarios and may even use different languages to write different applications and services. In this way, the above Token implementation method cannot meet the requirements.
Therefore, we need to use Jwt Bearer Token to solve the Token recognition problem in different applications.
. Net uses Jwt Bearer Token for OAuth
Microsoft. owin. security. the Access Token in the OAuth component is actually a serialized and encrypted string of an AuthenticationTicket object, the authentication of Access Token is the process of decrypting the encrypted string and deserializing it to obtain the AuthenticationTicket object.
For Access Token, whether it is Microsoft. owin. security. the implementation method of the OAuth component is Jwt or even custom format. The core of the OAuth component is how to include user information into a string token, and the correct user information can be restored through this string token. This process is abstracted as an ISecureDataFormat <TData> interface in the. Net Owin authentication solution. The generic TData type of authentication is AuthenticationTicket. Is the definition of ISecureDataFormat interface. The two methods are used to convert the string encryption token and the user information object. See ASP. NET has no magic -- ASP.. NET Identity encryption and decryption
Microsoft is also given in the previous article. owin. security. in the OAuth component, the default accesskey Token encryption and decryption object is TicketDataFormat, which is actually a type that implements the ISecureDataFormat interface, for serialization, encryption, and decryption of Data Objects, see ASP. NET has no magic -- ASP. NET Identity encryption and decryption:
It can be understood in this way. net implements OAuth Authentication Based on Jwt Bearer Token. owin. security. define an ISecureDataFormat <AuthenticationTicket> type based on the OAuth component.
Description of main Jwt attributes
Some important attributes of Jwt are described again before implementation:
● Issuer: the publisher, which contains information that will be verified in Jwt. The publisher of the Token is actually the authentication server itself.
● Audience: The publisher generates a Token based on the Audience, because the entire verification system is publisher-centered distributed and contains multiple applications, to ensure data security, a Token should only be valid for one of the applications. Therefore, Audience must be verified when Jwt is verified.
● Subject: a topic. It is generally used to save user information, such as the user name, in identity authentication.
The relationships between them are as follows:
A User represents a Subject. In OAuth, there is a Client concept. The Client of OAuth is equivalent to Audience. You have previously implemented Client Management. Now you can add a digital signature key for each Client, which is a Base64 encoded string of a 32-bit byte array. In addition, the HMAC algorithm is used to calculate the Token digest.
Implement a Jwt-based ISecureDataFormat <AuthenticationTicket>
The following describes how to implement the ISecureDataFormat:
1. Install the Microsoft. Owin. Security. Jwt component through Nuget:
Note: Microsoft implements a component used to parse the Jwt Bearer Token, but this component only implements the Unprotect method. Using this component can reduce the workload.
2. Understand the JwtFormat type in Microsoft. Owin. Security. Jwt:
Microsoft. Owin. Security. Jwt implements a JwtFormat object, which implements the required ISecureDataFormat interface:
However, the source code shows that this object does not implement the Protect method:
The implementation of its UnProtect method is as follows:
● Verify the publisher and Token signature and expiration time (Note: The verification operation is provided by the JwtSecurityTokenHandler type in the System. IdentityModel. Tokens. Jwt component ).
● After the verification is successful, obtain the user information contained in the Token.
3. Implement the Protect method of Jwt:
Complete code:
1 public class MyJwtFormat: ISecureDataFormat <AuthenticationTicket> 2 {3 // gets the Audience information from AuthenticationTicket. 4 private const string AudiencePropertyKey = "aud "; 5 6 private readonly string _ issuer = string. empty; 7 // the publisher of Jwt and the key for Digital Signature 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 Arg UmentNullException ("data"); 18} 19 // obtain the Audience name and information 20 string audienceId = data. Properties. Dictionary. 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 a SigningCredentials for Digital Signature Based on the key. This object uses 26 var keyByteArray = TextEncodings in JwtSecurityToken. base64Url. decode (audience. secret); 27 var signingKey = new inmemorypolicricsecuritykey (keyByteArray); 28 var signingCredentials = new SigningCredentials (signingKey, 29 SecurityAlgorithms. hmacSha256Signature, SecurityAlgorithms. sha256Digest); 30 // obtain the release time and expiration time 31 var issued = data. properties. issuedUtc; 32 var expires = data. properties. expiresUtc; 33 // create JwtToken object 34 var token = new JwtSecurityToken (_ issuer, 35 audienceId, 36 data. identity. claims, 37 issued. value. utcDateTime, 38 expires. value. utcDateTime, 39 signingCredentials); 40 // use JwtSecurityTokenHandler to serialize the Token object to a string of 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} 50}View Code
The above Code does the following:
● Obtain the Audience information from AuthenticationTicket (Note: AuthenticationTicket is. object used to save user information. In addition to user information, such as user name and user Claims, it also carries additional information such as the validity period of identity authentication. See. There are two ways to create AuthenticationTicket. One is to obtain the corresponding user information from the database and the authentication information from the configuration (or default) after checking that the logon information is correct during login, such as the validity period. In addition, it is obtained by deserializing the identity Token. The Protect method here is actually the Token serialization method, so the AuthenticationTicket obtained is created in the first method)
● Create a SignatureCredentials object for digital signature. This object represents the algorithm and key used for digital signature. The reason for creating this object is that the JwtSecurityToken object needs to be used to create the Token.
● Create a Token through the JwtSecurityToken object. The creation of this object requires the publisher (issuer), audience (audience), user Claims information, release time, validity period, and algorithms and keys required for digital signatures.
● Use JwtSecurityTokenHandler to serialize Token.
3. Add the Audience information to AuthenticationTicket.
The above mentioned the need for Audience information when creating a Token, And the Token is created through AuthenticationTicket. Therefore, you need to add the Audience information when creating the AuthenticationTicket. In addition, we also mentioned the two methods for creating AuthenticationTicket, the method used here is created during "login", while the "login" of OAuth is implemented through different types of "Authorization" methods, so the Audience information should be added, you only need to add the authorization code in the corresponding method (take the user name and password-based mode as an example, and copy the code in other methods ):
4. Add the JwtBearerAuthentication middleware used to parse the Token to the Audience (Client:
Audience or Client contains restricted resources. to access these resources, you need to parse the Token for authentication. Audience and Client are relatively independent, so it should restrict accessible Audience and have its own encryption key, and even verify the publisher to determine the token security. (Note: In this example, the authentication server and Client are included in the same application, and the actual application can separate them. This is a simple single-point logon system ).
5. Run the program
Use this Token to access restricted resources:
The following is the result of Base64 decoding of the Token. The Jwt information is displayed:
If you use the Token obtained by the Client test2, you cannot access the resources protected by test1:
Failed to authenticate. Go to the logon page:
OAuth and OpenID Connect
OAuth and OpenID Connect are two frequently used terms. The former has been introduced in this series of articles, and the OAuth is an authorization protocol, however, there is a conflict between identity authentication and authorization. As mentioned in the previous article, identity authentication aims to know who you are, authorization is to determine whether "you" has the permission to access resources. However, the OAuth-related content introduced in the previous article is used for identity authentication. Authorization protocols are used for identity authentication.
OpenID Connect is an Extended Authentication Protocol Based on the OAuth Protocol to make up for the defects of the OAuth protocol. It includes new advanced features such as Discovery Service, dynamic registration, Session management, and cancellation mechanism.
OAuth is used for identity authentication, but because OAuth is relatively simple and suitable for small projects, it is irrelevant to whether OAuth is an authorization protocol or an identity authentication protocol. It focuses on whether it can meet the needs, including the app. the names of UseOAuthBearerAuthentication methods are Authentication rather than Authorization. You can add the OAuth Bearer Authentication middleware to implement identity Authentication. OpenID Connect is more suitable for large projects.
Summary
This chapter introduces the implementation of Jwt and Jwt in. Net, and describes how to use Jwt Token to implement OAuth-based Identity Authentication in. Net. The main purpose of using Jwt Token is to solve the Token recognition problem of different applications.
Finally, I briefly explained the differences between OAuth and OpenID Connect. The key point of their choice is that the demand. For small applications, OAuth can be satisfied. Because OpenID Connect is very complex, if necessary, consider using open-source components such as IdentityServer.
Identity Authentication-related content for the moment here, for. Net security-related content can refer to the following blog, very comprehensive including identity authentication and. Net encryption and decryption, and other content: https://dotnetcodr.com/security-and-cryptography/
Refer:
Https://dzone.com/articles/whats-better-oauth-access-tokens-or-json-web-token
Https://stackoverflow.com/questions/32964774/oauth-or-jwt-which-one-to-use-and-why
Http://openid.net/specs/draft-jones-oauth-jwt-bearer-03.html
Https://tools.ietf.org/html/rfc7523
Https://auth0.com/learn/json-web-tokens/
Https://stackoverflow.com/questions/39239051/rs256-vs-hs256-whats-the-difference
Https://stackoverflow.com/questions/18677837/decoding-and-verifying-jwt-token-using-system-identitymodel-tokens-jwt
Http://www.c-sharpcorner.com/UploadFile/4b0136/openid-connect-availability-in-owin-security-components/
Https://security.stackexchange.com/questions/94995/oauth-2-vs-openid-connect-to-secure-api
Https://www.cnblogs.com/linianhui/archive/2017/05/30/openid-connect-core.html
Link: http://www.cnblogs.com/selimsong/p/8184904.html
ASP. NET has no magic-directory