Asp. NET no magic--asp.net OAuth, JWT, OpenID Connect

Source: Internet
Author: User

Tags: project mic Success Requirements upload also need summary secure introduction

The previous article introduced OAuth2.0 and how to use. NET to implement OAuth-based authentication, which complements the previous article by introducing the relationship and differences between OAuth and JWT and OpenID connect.

The main contents of this article are:
About JWT
. NET's JWT implementation
OAuth and JWT
. NET using JWT Bearer token for OAuth authentication
OAuth and OpenID Connect

  Note: This chapter content source code download:https://files.cnblogs.com/files/selimsong/OAuth2Demo_jwt.zip

About JWT

JWT (JSON Web Token) It is a data transfer standard based on JSON for security, and JWT has several features:
Compact: JWT is prepared for the web, so the data needs to be as small as possible to carry JWT in URLs, post parameters, or HTTP headers, and because of the small data, it also increases the speed of data transfer.
Self-contained: The Playload section of the JWT contains all the information that should be included, especially when the JWT is used for authentication playload contains the user's necessary identity information (note: It should not contain sensitive information) so that it does not need to go to the database to query the user information when authenticating.
Trusted: JWT is digitally signed to know if JWT has been tampered with during transmission, to ensure that the data is complete, and that the available signature algorithms are RS256 (rsa+sha-256), HS256 (hmac+sha-256), etc.

JWT has two uses, one for data interaction , because JWT is signed to guarantee the integrity of the data. It is also used to carry user information for authentication .

The JWT consists of three parts:
Header: Contains the signature algorithm and the token type (default is JWT). Such as:

  

  Note: ALG and Typ are abbreviations and are intended to reduce the size of the JWT.

Playload: Contains the content of the information that JWT carries, Playload contains 3 types of claim (declaration) definitions, which are standard, such as ISS (publisher of ISSUER,JWT), sub (the user represented by SUBJECT,JWT), AUD ( AUDIENCE,JWT), exp (Expiration TIME,JWT expiration time), and some are public contracts such as: http://www.iana.org/assignments/jwt/ Jwt.xhtml, which is also privately-defined, is used to store specific information.
The structure of the playload is as follows:

  

Signature: Contains the header and Playload's Base64url encoded signature results, which are calculated as follows:

  

The final three sections are encoded using the Base64url notation "." To separate, here is an example of a complete JWT:

  

  Note: The data in JWT is transparent, so that anyone who gets the data can see the content in the form of Base64url, and the signature simply guarantees that the content is not tampered with, so it is not possible to include sensitive data in the JWT. The above examples are from https://jwt.io/introduction/ 

. NET's JWT implementation

JWT is a standard that can be seen in many different languages on https://jwt.io/for JWT implementations. NET one of the implementations is the SYSTEM.IDENTITYMODEL.TOKENS.JWT component, which is implemented by Microsoft, and it has two important types, namely:
  Note: As can be seen from the name (IdentityModel), this implementation of Microsoft is mainly used for authentication, if the purpose of using JWT is not authentication you can choose other components or custom implementations.
Jwtsecuritytoken: This type is a package of JWT, with the exception of the three elements of JWT (Header, Playload, Signature), as well as some extensions such as subject, iusser, audiences, expiration, Signature algorithm, signature key and other important attributes.
is a partial definition of Jwtsecuritytoken:

  

Jwtsecuritytokenhandler: This object is used to manipulate JWT, such as the creation of JWT, validation (including publishers, receivers, signatures, etc.), serialization and deserialization of JWT (conversion between string form and object form)
is a partial definition of Jwtsecuritytokenhandler:

  

OAuth and JWT

OAuth and JWT The former is an authorization protocol the latter is an information-safe transmission standard that does not seem to have anything to do with it, but in fact OAuth's access token is implemented in a way that is JWT.
Why use JWT as an OAuth access token? First, take a look at the access token generated in the previous article:

  

It is an encrypted string that contains information about the user, but the string can only be decrypted by the application using the Microsoft.Owin.Security.OAuth component (excluding the implementation of the referenced source code). and also to ensure that the encryption key is the same decryption. But OAuth is often used in distributed scenarios, and even uses different languages to write different applications and services. In this way, the above token can not meet the needs of the implementation.
It is therefore necessary to use JWT Bearer tokens to solve token recognition problems in different applications .

. NET using JWT Bearer token for OAuth authentication

In the previous article, it was mentioned that the generation of access tokens in the Microsoft.Owin.Security.OAuth component was actually a string that was serialized and encrypted on a Authenticationticket object, and Access Token validation is the process of decrypting and deserializing the encrypted string to get the Authenticationticket object.
For access tokens, whether the Microsoft.Owin.Security.OAuth component is implemented or JWT, or even a custom format, its core is how to include user information in a string token. And be able to restore the correct user information through this string token . For this one process in. NET is abstracted as a isecuredataformat<tdata> interface in the Owin authentication solution, where the generic Tdata type for authentication is authenticationticket. Is the definition of the Isecuredataformat interface, and its two methods are used for the conversion between the string encryption token and the user information object, can refer to the ASP. NET no magic--asp.net identity encryption and decryption

  

In the previous article also given the Microsoft.Owin.Security.OAuth component, the default access token plus decryption object is Ticketdataformat, This object is actually a type that implements the Isecuredataformat interface, which can be used to accomplish the serialization and decryption of data objects through data protector, and it is possible to refer to ASP. NET no magic--asp.net identity encryption and decryption:

  

You can understand that in the. NET implementation of the JWT Bearer token-based OAuth authentication, you only need to customize a isecuredataformat< on the basis of the Microsoft.Owin.Security.OAuth component Authenticationticket> type .

Description of JWT Main properties

Some important properties of JWT are described again before implementation:
Issuer: The publisher, the information that the JWT contains and validates, the token publisher, which is actually the authentication server itself.
Audience: Audience, the publisher generates a token that is generated based on the audience, because the entire authentication system is publisher-centric distributed with multiple applications, in order to ensure data security a token should only be valid for one of the applications, The audience is also validated when validating the JWT.
Subject: A topic that is typically used to save user information, such as a user name, in authentication.

Their three relationships are as follows:

  

The user represents subject, which has the concept of client in OAuth, and the client of OAuth is equivalent to audience. The client was previously managed, and now adds a digital signature key to each client that is a BASE64 encoded string of 32-bit byte arrays. Also here is the use of the HMAC algorithm to complete the digest calculation of tokens.

  

Implement a JWT-based isecuredataformat<authenticationticket>

Here's how to implement this Isecuredataformat:
1. Install the MICROSOFT.OWIN.SECURITY.JWT component through NuGet:
Note: Microsoft has implemented a component to resolve JWT Bearer tokens, but the component only implements the Unprotect method, which can be reduced by using this component development.

  

2. Learn about the Jwtformat types in MICROSOFT.OWIN.SECURITY.JWT:
MICROSOFT.OWIN.SECURITY.JWT implements a Jwtformat object that exactly implements the required Isecuredataformat interface:

  

However, it is learned from the source that the object does not implement the Protect method:

  

and the implementation of its Unprotect method mainly works as follows:

  

Verify the signature, expiration time, and so on for the publisher and token ( Note: The validation action is provided by the Jwtsecuritytokenhandler type in the SYSTEM.IDENTITYMODEL.TOKENS.JWT component ).
Obtain the user information contained in the token after the validation is successful.

3. Protect method to implement JWT:

  

Full code:

1      Public classMyjwtformat:isecuredataformat<authenticationticket>2     {3         //used to get audience information from Authenticationticket4         Private Const stringAudiencepropertykey ="AUD";5 6         Private ReadOnly string_issuer =string. Empty;7         //the publisher of the JWT and the key used for the digital signature8          PublicMyjwtformat (stringissuer)9         {Ten_issuer =issuer; One         } A  -          Public stringProtect (authenticationticket data) -         { the             if(Data = =NULL) -             { -                 Throw NewArgumentNullException ("Data"); -             } +             //get the audience name and its information -             stringAudienceid = data. Properties.Dictionary.ContainsKey (Audiencepropertykey)? +Data. Properties.dictionary[audiencepropertykey]:NULL; A             if(string. Isnullorwhitespace (Audienceid))Throw NewInvalidOperationException ("Authenticationticket.properties does not include audience"); at             varAudience = ClientRepository.Clients.Where (c = c.id = =Audienceid). FirstOrDefault (); -             if(Audience = =NULL)Throw NewInvalidOperationException ("audience invalid."); -             //creates a signingcredentials for digital signatures based on the key, which is used in Jwtsecuritytoken -             varKeybytearray =TextEncodings.Base64Url.Decode (audience. Secret); -             varSigningkey =NewInmemorysymmetricsecuritykey (keybytearray); -             varSigningcredentials =Newsigningcredentials (Signingkey, in securityalgorithms.hmacsha256signature, securityalgorithms.sha256digest); -             //get publish time and Expiration Time to             varIssued =data. PROPERTIES.ISSUEDUTC; +             varexpires =data. PROPERTIES.EXPIRESUTC; -             //Create a Jwttoken object the             vartoken =NewJwtsecuritytoken (_issuer, * Audienceid, $ data. Identity.claims,Panax Notoginseng issued. Value.utcdatetime, - expires. Value.utcdatetime, the signingcredentials); +             //serializing a token object into a string using Jwtsecuritytokenhandler A             varHandler =NewJwtsecuritytokenhandler (); the             varJWT =handler. Writetoken (token); +             returnJWT; -         } $  $          PublicAuthenticationticket Unprotect (stringprotectedtext) -         { -             Throw Newnotimplementedexception (); the         } -}
View Code  

The above code does a few things:
Get audience information from Authenticationticket (Note: Authenticationticket is the object used in. NET to hold user information , in addition to user information, additional information such as the user name and the user's claims, as well as the validity period of the authentication, are shown. There are two ways to create a authenticationticket, one is to log in, after judging the login information is correct, obtain the corresponding user information from the database and from the configuration (or the default) to obtain authentication information, such as the expiration date. The other is through the deserialization of identity token acquisition . The Protect method here is actually the method of serializing tokens, so the authenticationticket it gets is created by the first total method)

  

Creates a Signaturecredentials object for digital signatures that represents an algorithm for digital signatures and their keys . The object was created only because the Jwtsecuritytoken object needed it to complete token creation.
Creating tokens from Jwtsecuritytoken objects requires the publisher (issuer), audience (audience), user claims information, publish time, expiration date, and algorithms and keys required for digital signatures.
The token serialization is done through Jwtsecuritytokenhandler.

3. Add audience information to the Authenticationticket.
The above refers to the need to audience information when creating tokens, and token is created through authenticationticket, so you need to add audience information when creating Authenticationticket. In addition, the above also mentions two ways to create Authenticationticket, the method used here is created when "login", and OAuth "login" is implemented by different types of "authorization" method, so to add audience information, Just add it in the appropriate way in the authorization code (for example, based on the user name, password mode, other methods to copy the code can be):

  

4. Add the Jwtbearerauthentication middleware for audience (Client) to resolve tokens:

  

Audience or the client contains a restricted resource and needs to parse token to complete the authentication when it accesses these resources. While audience or client is relatively independent, it should limit the accessible audience and have their own encryption keys, and even need to verify the publisher to determine the security of tokens. ( Note: In this example, both the authentication server and the client are included in the same application, and the actual application can separate it, which is a simple single sign-on system ).

5. Running the program

  

Use this token to access restricted resources normally:

  

Here is the result of decoding the token Base64, and you can see the information that the JWT contains:

  

If you use tokens obtained by this client test2, you will not be able to access test1 protected resources:

  

Authentication failed, jump login page:

  

OAuth and OpenID Connect

OAuth and OpenID Connect are two nouns that often appear together, the former has been described in this series of articles, OAuth is an authorization protocol, but the paradox is that authentication and authorization are actually two concepts, as mentioned in the previous article, the purpose of authentication is to know "you" Who is, and authorization is to determine whether "you" have access to resources. However, the OAuth-related content that was introduced from the previous article is used for authentication. The authorization protocol is used for authentication, so it is contradictory.
OpenID Connect is an authentication protocol that complements the OAuth protocol by supplementing the OAuth protocol. It includes new advanced features such as discovery Services, dynamic registration, session management, logoff mechanisms, and more.
Using OAuth for authentication is only because OAuth is relatively simple and suitable for small projects, regardless of whether OAuth is an authorization protocol or an authentication protocol, and it focuses on meeting needs , including apps. The Useoauthbearerauthentication method names are authentication instead of authorization, and authentication is achieved by adding OAuth bearer authentication middleware. OpenID Connect is more suitable for large projects and is no longer covered here.

Summary

This chapter describes the implementation of JWT and JWT in. NET, and describes how to implement OAuth-based authentication using JWT tokens in. Net. The main purpose of using JWT tokens is to solve token recognition problems for different applications.
Finally, the difference between OAuth and OpenID Connect is simply explained, and the key to their trade-offs is demand, which is satisfying for small applications, and because OpenID Connect is very complex, If there is a need, you can also consider using open source components such as identityserver.

  

Content related to authentication temporarily to this, about. NET security related content can refer to the following blog, very comprehensive contains the authentication as well. NET in addition and decryption content: https://dotnetcodr.com/security-and-cryptography/

Reference:

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

This article link: http://www.cnblogs.com/selimsong/p/8184904.html

Asp. NET no magic--Directory

ASP. NET no magic--asp.net OAuth, JWT, OpenID Connect

Related Article

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.