Original link: uriotnews.com/?s=oauth2.0…

I. Authentication and authorization

From the dawn of computer-based applications, one of the most common and complex issues faced by almost every developer in their career is security. These kinds of questions mean thinking about understanding who is providing what data/information, as well as many other things related to timing, validation, re-validation, and so on.

All security-related concerns can be broken down into two categories: Authentication and Authorization.

Although the terms are often used interchangeably, they essentially denote different functions. Let’s try to polish up memory and define these concepts again.

certification

Authentication is the process by which a user, website, or application proves that they are who they claim to be by providing a valid certificate or authentication. Authentication is often verified by username and password, and sometimes by other information that is only known to the user. Such information or elements are called factors. Based on these factors, any authentication mechanism can be divided into the following three categories:

  1. Single-factor authentication: Depends only on the user name and password
  2. Two-factor authentication: In addition to the username and password, a piece of confidential information is required (for example, a bank website may require users to enter a PIN that only they know)
  3. Multi-factor authentication (MFA): The use of two or more security factors from different categories (e.g. the hospital system requires a username and password + a security verification code received by the user’s smartphone + fingerprint information)

authorization

Authorization refers to the process of verifying what a user can access. During authorization, a user/application is allowed to access specific APIs/ modules only after its permission level is determined. Typically, authorization occurs after the user’s identity is authenticated.

Authorization is achieved through the use of policies and rules.

Authentication vs Authorization

While certification and licensing are often used interchangeably, try using the “soda and cocktail” analogy. A cocktail, on the other hand, is a combination of many ingredients. Soda might be one of them, but not just one.

So it’s not true that soda is the same as a cocktail or that a cocktail is bubbling soda. Similarly, authentication and authorization are not the same terms; Well done, they can complement each other, but they are fundamentally different.

  certification authorization
1 Determine who the user claims to be Determine the permissions that users can access
2 Verify users with valid credentials Verify access by rules and policies
3 Before the authorization Executed after the authentication is successful
4 With ID Tokens With Access Tokens

In a real scenario, authentication and authorization are used together to protect resources. You should not be allowed access to resources until you can prove your identity; Even if they prove their identity, they should still be denied access without it.

Implementation mechanisms

There are many ways to achieve authentication and authorization, but the most popular one is token-based.

What is token-based authentication?

Token based authentication and authorization (Token – -based authentication/authorization) is a technology: when the user input a somewhere after his user name and password, as the exchange will get a generated only encrypted Token. This token is then used in place of the login credentials to access the protected page or resource.

The point of this approach is to ensure that each request sent to the server is accompanied by a signed token, which the server uses to verify authenticity before responding to the request.

What is the token?

A “token” is a piece of data generated by the server that contains information that uniquely identifies a user, typically generated as a long string of random characters and numbers.

For example might look like this: cc7112734bbde748b7708b0284233419, or more complex such as: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtZXNzYWdlIjoiSldUIFJ1bGVzISIsImlhdCI6MTQ1OTQ0ODExOSwiZXhwIjoxNDU5NDU0NTE5fQ.\-y IVBD5b73C75osbmwwshQNRC7frWUYrqa TjTpza2y4.

The token itself is meaningless and useless, but when combined with a proper tokenization system, it becomes an important part of application security.

Why use a token?

Using tokens has the following advantages over traditional means such as cookies:

  • Stateless: The token is self-contained, containing all the information used for authentication. This is great for scalability and frees the server from having to store sessions
  • Can be generated anywhere: token generation and validation are decouplable, making it possible to sign tokens using a separate server or even a different vendor, such as Auth0
  • Fine-grained access control: Through token payload, users can easily specify more roles and permissions than just the resources they can access

Token-based implementation

Although specific implementations vary, they generally involve the following steps:

  1. Users request access by user name and password
  2. Application authentication credentials
  3. The application issues a signed token to the client
  4. The client stores the token and sends it along with each subsequent request
  5. The server validates the token and responds to the data

While there are no restrictions on how your application should be implemented, the Internet Engineering Task Force (IETF) does define some standards. Two of the most popular are:

  1. OAuth 2.0 (RFC 6749 and RFC 6750).

  2. JWT (RFC 7519).

II. Understand OAuth 2.0

We have refreshed our knowledge of authentication and authorization, and will learn about token-based authentication. In this section, take a look at one of the most commonly used implementations: OAuth 2.0.

The 2.0 introduction

In the traditional C/S model, the client requests the server’s protected resources by having the server authenticate the credentials of the resource owner. Resource owners share their credentials with third-party applications, giving them access to restricted resources. This credential sharing behavior creates several problems and limitations, some of which are listed below:

  • Third-party applications require the credentials of the storage resource owner to continue to use, typically storing a password in plain text
  • Despite the security weaknesses inherent in passwords, the server must still support password authentication
  • For the limited resources of resource owners, third-party applications get too broad access rights; Put resource owners in a position where they cannot restrict access duration or restrict access to a subset of resources
  • The resource owner cannot revoke access to individual third parties without changing the passwords of all third parties

OAuth addresses these issues by introducing an authentication layer that separates the role of the client from that of the resource owner. So:

OAuth is a licensing agreement that allows users to license restricted access to their resources on one site to another site without having to disclose their credentials

OAuth provides a “secure proxy access” capability for clients to access server resources on behalf of the resource owner. OAuth specifies a process by which a resource owner authorizes third parties to access its server resources without sharing its credentials.

Here’s an example:

Parking key

You know how some cars have “parking keys”? If you haven’t already, there are some (yes, the really luxurious ones!) models. It comes with a special key that can be handed to the valet when parked. Unlike your normal key, this one doesn’t allow the car to go as far as a mile or two.

Some parking keys won’t open the trunk, others won’t access the car phone’s address book. Whatever such restrictions are, the idea is the same: you give someone limited access to your car through a special key, but your normal key unlocks everything.

Similarly, the parking keys in OAuth are Access Tokens that allow different levels of Access to resources.

The 2.0 term

Roles: The OAuth2.0 specification defines four types of Roles.

  1. Resource Owner: An entity that has the ability to authorize access to protected resources. When this entity is a person, it represents an end-user.
  2. Resource Server Resource Server: A Server that stores protected resources and can accept and respond to requests for protected resources using access tokens.
  3. The Client Client: An application that initiates a request for a protected resource and represents the resource owner and holds its credentials. The term”client“Does not imply any implementation characteristics (such as whether the application is running on a server, desktop, or other device).
  4. Authorization Server: After the resource owner is successfully authenticated and authorized, the Server grants the access token to the client.

Tokens: There are two types of Tokens.

  1. Access Token: An Access Token is a string representing an authorization granted to a client. This string is usually obscure to the user. Tokens represent special access scope and duration granted by the resource owner and enforced by the resource server and authorization server.

    A token may represent an identifier used to retrieve authentication information, or it may self-contain authentication information in a verifiable manner, such as containing some data and signatures.

  2. Refresh Token: The Refresh Token is used to obtain credentials to access the Token. The update token is issued by the authorization server to the client and a new access token is obtained with the update token when the access token is invalid or expired; It may also be used to obtain additional access tokens with the same or narrower access scope (these access tokens may have a shorter lifetime and fewer permissions than access tokens authorized by the resource owner).

    Whether to issue an update token is at the discretion of the authorization server; If issued, it will be used for subsequent issuance of access tokens.

Unlike request tokens, update tokens are designed for authorization servers and are not sent to resource servers.

Authorization Grant: Authorization is a credential that indicates the resource owner’s approval (access to its protected resources) and is used by clients to obtain access tokens. The OAuth 2.0 specification defines four licensing types:

  1. The Authorization Code is obtained from an Authorization server that acts as an intermediary between the client and the resource owner. Instead of requesting authorization directly from the resource owner, the client directs the resource owner to the authorization server, which directs the resource owner back to the client with an authorization code.
  2. Implicit Grant: Instead of sending an authorization code to the client, the client directly obtains an access token.
  3. Resource Owner password credentials Resource Owner Password Credentials (ROPC): Resource owner password credentials (such as user names and passwords) can be used directly as permissions to obtain access tokens. ROPC should only be used when a high trust level is required between the resource owner and the client (for example, the client is part of the operating system of the host device, or a high-privilege application) and several other licenses (such as license codes) are not available.
  4. Client Credentials: When authorization is limited to protected resources under the control of the Client, or to protected resources previously agreed with the authorization server, Client Credentials (or other forms of Client authentication) can be used as authorization. Typically, a client requests access to a protected resource on behalf of itself (which is also the resource owner) or a client based on a prior agreement with the resource server.

Understanding these terms is critical when working with OAuth 2.0. So, try to use an example as well.

Imagine a subway system. This is the typical stopping process: A commuter buys a ride from a ticket machine or window that is permitted to be legal for a limited time or number of stops. After that, the passenger checks the ticket at the gate, the ticket is legal to be allowed to enter, can take the train.

Use the subway as a metaphor for OAuth

The above scenario can be compared to the following OAuth 2.0 characters:

The passenger (client) intends to use the subway (a protected resource), so he/she has to buy a ticket from a ticket machine or ticket window (a resource server) first. The ticketing system (authorization server) permits access based on tickets (tokens) on behalf of the METRO department (resource owner).

Use the subway as a metaphor for OAuth

OAuth 2.0 control flow

An OAuth 2.0 process can be shown in the following figure:

OAuth 2.0 control flow

The 2.0 cases

OAuth 2.0 decouples authentication from authorization decisions. Properly designed OAuth 2.0 tokens can support both fine-grained and coarse-grained authorization. For any scenario where resources/data stored somewhere are accessed from another place (server/application), OAuth 2.0 is one of the most applicable methods.

Listed below are some scenarios where we will attempt to understand the OAuth 2.0 use case through a wearable device example.

Take the sports bracelet for example. Suppose Alice bought one and used the matching bracelet app on the mobile terminal to track and analyze the movement process. So what would the process look like?

  • First, Alice needs to create a profile in the wristband app. One way is to create a form using the profile provided by the app. The other way is to have the app visit other apps and pull up the profile information Alice already has stored there — take FriendBook, an apparently fictional social media site.
  • The wristband app redirects to the FriendBook login screen. Once Alice has successfully logged in with her credentials, she will see a consent page asking her or asking her to verify what information she wants to share and what she is allowed to access stored on FriendBook. After confirmation, the bracelet app can pull and use data from FriendBook using OAuth 2.0.
  • The wearable sends data to the wristband app, which synchronizes the data to a server for archiving and analysis.

Client password: (although authentication using OAuth 2.0 should be avoided). Alice does not have to create a new password; Instead, she uses a password she already created on the FriendBook server.

Web server: The app of wearable devices does not need to initiate login for every operation. Alice will share or pull data from FriendBook, and the bracelet app will be able to access that data in a server-to-server manner.

User agent: The wristband app acts as an agent for its application server, synchronizing data from the primary server. With OAuth 2.0 for this authorization, the agent can access exactly the resources (data) on the server.

3. Understand the JWT

Let’s look at JWT.

JSON Web Token (JWT), often pronounced “JOT,” is a standard that defines the secure transfer of information between parties in compact, self-contained JSON objects. It contains declarative information, especially for space-constrained environments such as HTTP; This information can be verified and trusted because it is digitally signed. JWT can be signed with a key (such as HMAC) or a public/private key pair (RSA or ECDSA).

The two features of JWT are:

  • Compact: Because of its relatively small size, the JWT can be sent by URL, as a POST parameter, or in an HTTP header.
  • Self-contained Self-contained: A JWT contains all the required information about an entity to avoid querying the database multiple times. JWT recipients also do not need to invoke the server to validate the token.

These tokens can be signed, encrypted, or both. Signed tokens are used to verify token integrity, while encrypted tokens are used to hide declarations.

Note: As the name implies, JWT is JSON, which means it contains key-value pairs. While there is no limit to how long keys and values can be in terms of JSON legality and party consistency, most standards follow the three-letter key format.

JWT term

JWT is represented by point (.) A sequence of three split strings would typically look like this:

AAAAA.BBBBB.CCCCC

These substrings are called headers, payloads, and signatures.

The head the Header

While there is no limit to what can be put in the head as long as there is agreement among the parties concerned, it usually consists of two parts:

  1. typ: indicates the token type, and the value isJWT
  2. alg: indicates the algorithm to sign the token, such asHMAC,RSA,SHA

Load content

The second part of the JWT represents the payload, which consists of claims.

A declaration is information about an entity and any additional data. In a JWT, the declaration is represented by a key. These declarations are context-dependent and should be handled and understood accordingly, but there are several standard rules that apply to declarations according to each specification:

  1. In a collection of JWT declarations, the name of each declaration must be unique
  2. For the processing logic of JWT,Must beTo ensure this uniqueness, either reject duplicate names or use a JSON processor to return the last lexical name in the duplicate item
  3. Applications that use JWT should be clear about the declaration criteria they choose and define requirements and options
  4. Because one of the core goals of JWT is simplicity, all names should be short

An example of a possible load:

{ 
    "sub": "1234567890"."name": "Alice"."admin": true
}
Copy the code

Declarations in the payload can be subdivided into the following three types:

Registered declaration

There are some declarations registered at IANA(dzone.com/refcardz/co…) In the JSON Web Token Declaration registry. These declarations are not mandatory or implemented in all cases, rather they are registered as a starting point for providing a useful collection.

Some of the things to know are:

  1. Iss (Issuer): States the issuer of the JWT. Handling this declaration usually varies from application to application. The “iss” value is a case-sensitive string containing either a normal string or a URL. This declaration is optional
  2. Sub (subject): indicates the JWT principal (user). Values must be either globally unique or locally unique within the scope of the issuer context. The handling of this declaration also often varies from application to application. The “sub” value is a case-sensitive string containing either a normal string or a URL. This declaration is optional
  3. Aud (audience): indicates the target recipient of JWT. JWT must be rejected if the claim exists and the party handling the claim cannot self-authenticate with the value of “aud”. In most cases, this value is an array of case-sensitive strings (either a normal string or a URL). This declaration is optional
  4. Exp (expiration): expiration time, i.e. processing JWT at or after that time is never acceptable. The value is usually a timestamp in seconds since epoch. This declaration is optional
  5. NBF (not before) : indicates a time before which processing JWT is never acceptable. Its value is usually timestamp in seconds. This declaration is optional
  6. Iat (Issued at): JWT time Can be used to judge the life of JWT. It has to be a timestamp. This declaration is optional
  7. Jti (JWT ID): Provide a unique identifier for the JWT, whose value must be difficult to repeat in case the JWT is executed repeatedly. This declaration is optional

A public statement

The names of such declarations can be arbitrarily defined by JWT users. However, to prevent conflicts, any new name should be registered in the IANA “JSON Web Token Claims” registry, or defined as a URI containing a conflict-proof namespace, etc.

In any case, the definition of names and values takes reasonable precautions to ensure that they are controlled within the namespace in which they are defined.

Private statement

This can be interpreted as creating custom declarations to share information specifications within the application, and can be any declaration name in addition to the above two. Unlike public declarations, private declarations are subject to conflicts and should be used with care.

The signature

The signature is first generated by Base64 encoding of the header and payload, and is then combined with a key, preferably signed by the algorithm specified in the header.

The signature is used to verify that the name of the JWT sender matches that of the JWT sender and that the message is not changed during transmission. For example, if you created a signature using the HMAC SHA256 algorithm token, you would do something like this:

HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
Copy the code

A more complete example

Observe the following JWT signatures:

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzYXRpc2giLCJhdWQiOiJteWFwcCIsIkNVU1QiOiIxIiwiZXhwIjoxNTY2MjE0NTg1LCJpc3M iOiJhdXRoLWFwcCJ9.WknG6jiM_vAaflLnKyjlXh5BrM4MUJR9dFrVx-XE3zRVWiyXeIVzI-OomFh0vVHRwrK3-Tttg0HyKBTnCA3mSgCopy the code

The signature is encoded using the HS512 algorithm and contains the following information:

Header: { 
    "alg": "HS512"."typ": "JWT"
} 
Payload: { 
    "sub": "satish"."aud": "myapp"."CUST": "1"."exp": 1566214585, 
    "iss": "my-auth-app"
}
Copy the code

JWT cases

certification

When the user logs in successfully with his credentials, an ID token is returned. According to the OpenID Connect (OIDC) specification, this ID token is a JWT.

authorization

Once the user logs in successfully, the application may request access to routes, services, resources, and so on on behalf of the user. To do this, you will use an access token, probably in the form of JWT. Each subsequent request also contains the access token. Single sign-on (SSO) is widely used because JWT is inexpensive and can easily be used for cross-domain access.

Information exchange

Since it can be signed, JWT is a great way to securely transfer information between multiple parties, which means you can be sure the sender’s name matches the sender’s name. In addition, a JWT structure allows you to verify that the content has not been tampered with.

Why use JWT?

The decoupling

The biggest advantage of JWT (over user session management using random-in-memory tokens) is that it allows agents to authenticate logic to third party servers:

  • A centralized, in-house custom developed authentication server
  • More typically, you use LDAP, a commercial product that can issue JWT
  • You can even use a purely third-party certification provider

The authentication logic/server can be completely separated from the application server, eliminating the need to share password digests between applications.

stateless

Because the JWT is self-contained and does not need to keep tokens between requests in memory, the application server can be completely stateless. The authentication server can issue a token, send it back and discard it immediately.

compact

JSON is simpler than XML, so when it is encoded, a JWT is smaller than a SAML token. This makes JWT a good choice for delivery in HTML and HTTP environments.

A more secure

To sign, JWT can use a public/private key pair in the form of x.509 certificates. A JWT can also be symmetrically signed by sharing a key that uses the HMAC algorithm. And while SAML tokens can also use public/private key pairs like JWT, it is very difficult to sign XML with an XML digital signature algorithm without introducing unknown security vulnerabilities compared to the simplicity of signing JSON.

A more general

JSON processors are more common in most programming languages because they map directly to objects. In contrast, XML has no natural document-to-object mapping. This means that JWT is easier to use than SAML.

Easier to handle

JWT is designed for Internet scale, which means it’s easier to process on user devices, especially mobile.

JWT: Points to consider

Despite the advantages and disadvantages mentioned above, the JWT standard has its own problems:

  • If a user account needs to be blocked or frozen, the application has to wait for the token to expire before it can be shut down completely.
  • If a user is updating a password (such as in the case of account hijacking) and an authentication has been performed previously, the token generated by the previous password will remain valid until it expires.
  • In the standard implementation, no “update” token is specified. Therefore, the user will be re-authenticated after expiration.
  • It is impossible to break a token without violating the “stateless” aspect of the JWT token, which remains valid until it expires, even after it has been removed from the browser.

In response to these adjustments, some JWT libraries add a layer on top of the standard implementation and allow for updated token mechanisms, as well as features such as forcing users to re-authenticate if necessary.

JWT: Best practices

Before implementing JWT, let’s take a look at some best practices to ensure token-based authentication is properly used in your application.

  1. Ensure safety. The signature key should be treated like any other credential and presented only to the service that must require it.
  2. Do not add sensitive information to the payload. The token is signed in a form that is difficult to manipulate and easy to decode. Add minimal declarations to the load to ensure performance and security.
  3. Set the expiration time for the token. Technically, once a token is signed — it is permanently valid unless the key used to sign it changes, or an expiration date is explicitly set. This can be a hazard, so there should be an expiration and revocation strategy for tokens.
  4. Embrace the HTTPS. Do not send tokens to non-HTTPS connections, as those requests can be intercepted and the token is compromised.
  5. Review all of your authorization use cases. Adding a secondary token validation system to ensure that tokens are generated from your server, for example, may not be common practice, but may be necessary to fulfill your requirements.

More and more

Implement role-based access control with Spring Boot 2 and JWT






–End–






Search fewelife concern public number reprint please indicate the source