OAuth 2.0 极简教程 (The OAuth 2.0 Authorization Framework)

What is OAuth 2.0?

OAuth (Open Authorization) is an open standard that allows users to authorize third-party mobile applications to access their information stored on another service provider without the need to provide user names and passwords to third-party mobile applications or share all of their data , OAuth2.0 is not compatible with OAuth 1.0.

Simply put, this is an authorization mechanism. The data owner (Resource Owner) tells the system that they agree to authorize a third party application (third party Application) to enter the system (Server) to obtain these data. The system thus generates a short-term entry token (token), which is used in place of a password for use by third-party applications.

In the traditional client-server authentication model, the client requests protected resources from the server by using an authentication certificate to the server.

In order to provide third-party applications to access these resources, resources need to share authentication information such as user names and passwords with the third party. This brings some problems and limitations:

o A third-party application is required to store the credentials of the resource owner for future use, usually in clear text of the password.

o The server is required to support the inherent security weaknesses of password verification.

o Third-party applications gain extensive access to resources. Thus, the resource owner does not have any
limited duration or the ability to access a limited subset.

o The resource owner cannot revoke access to a single third party. If you must do this, you have to change the third-party password. That will affect all authorized third parties.

OAuth solves these problems by introducing an authorization layer.

In OAuth, the client requests access to the controlled resource by the resource owner and managed by the resource server, and a set of credentials different from the resource—access token is issued. It is issued by the authorization server to the third-party client, and Approved by the resource owner. The client obtains an access token (a string representing a string: specific scope, lifetime, and other access attributes, etc.), and uses it to access protected resources hosted by the resource server.

There are four domain models (roles, Roles) in OAuth2:

  • Resource Owner: The resource owner is the WeChat user mentioned above

  • Resource Server: The resource server is the WeChat server mentioned above, which provides basic information of WeChat users to third-party applications

  • Client: The third-party application client is the third-party application that your company is developing in the above

  • Authorication Server: The role of authorization server can be understood as the middle layer that manages the relationship between the remaining three

It is not difficult to see that the key to OAuht2's solution to the problem is to use the authorization server to provide an access credential to third-party applications, so that third-party applications can obtain resources without knowing the resource owner’s account and password on the resource server The owner's protected resource on the resource server, where the protected resource is the name and profile picture of the WeChat user.

OAuth 2.0 problem scenario

To understand where OAuth is applicable, let me give a hypothetical example.

There is a "cloud printing" website, which can print out the user's photos stored in Google. In order to use the service, users must allow "Cloud Printing" to read their photos stored on Google.

Cloud printing

The problem is that only with the user's authorization, Google will allow "cloud printing" to read these photos.

So, how does "Yun Chong Yin" obtain user authorization?

The traditional method is that users tell "Cloud Chongyin" their Google username and password, and the latter can read the user's photos. This approach has the following serious disadvantages.

(1) "Cloud Print" will save the user's password for subsequent services, which is very insecure.
(2) Google has to deploy password login, and we know that simple password login is not safe.
(3) "Cloud Chongyin" has the right to obtain all the data stored by users in Google, and users cannot limit the scope and validity period of "Cloud Chongyin" authorization.
(4) Only by changing the password can the user withdraw the power granted to "Cloud Printing". But doing so will invalidate all other third-party applications authorized by the user.
(5) As long as a third-party application is cracked, the user password will be leaked, and all password-protected data will leak.

OAuth was born to solve these problems.

Problem solving ideas

All problems in the computer can be solved by adding an intermediate layer.

OAuth sets up an authorization layer between the "client" and the "service provider". The "client" cannot directly log in to the "service provider", but can only log in to the authorization layer to distinguish the user from the client. The token used by the "client" to log in to the authorization layer is different from the user's password. The user can specify the scope and validity period of the authorization layer token when logging in.

After the "client" logs in to the authorization layer, the "service provider" will open the user's stored information to the "client" according to the scope and validity of the token.

Glossary

Before explaining OAuth 2.0 in detail, you need to understand a few specific terms. They are essential to understand the following explanation, especially a few pictures.

(1) Third-party application: third-party application, also called "client" in this article, that is, "cloud printing" in the example in the previous section.

(2) HTTP service: HTTP service provider, referred to as "service provider" in this article, that is, Google in the example in the previous section.

(3) Resource Owner: Resource Owner, also called "user" in this article.

(4) User Agent: User agent, in this article refers to the browser.

(5) Authorization server: Authentication server, which is a server specially used by service providers to process authentication.

(6) Resource server: Resource server, that is, the server where the service provider stores user-generated resources. It and the authentication server can be the same server or different servers.

Knowing the above terms, it is not difficult to understand that the role of OAuth is to allow the "client" to securely and controllably obtain the authorization of the "user" and interact with the "service provider".

OAuth 2.0 protocol operation process (Protocol Flow)

The operation flow of OAuth 2.0 is shown in the figure below, which is taken from RFC 6749. (Http://www.rfcreader.com/#rfc6749)

The abstract OAuth 2.0 flow illustrated in Figure 1 describes the
interaction between the four roles and includes the following steps:

(A) The client requests authorization from the resource owner. The authorization request can be made directly to the resource owner (as shown), or preferably indirectly via the authorization server as an intermediary.

(B) The client receives an authorization grant, which is a credential representing the resource owner's authorization, expressed using one of four grant types defined in this specification or using an extension grant type. The authorization grant type depends on the method used by the client to request authorization and the types supported by the authorization server. An authorization grant is a credential representing the resource owner's authorization (to access its protected resources) used by the client to obtain an access token. This specification defines four grant types -- authorization code, implicit, resource owner password credentials, and client credentials -- as well as an extensibility mechanism for defining additional types.

(C) The client requests an access token by authenticating with the authorization server and presenting the authorization grant.

(D) The authorization server authenticates the client and validates the authorization grant, and if valid, issues an access token.

(E) The client requests the protected resource from the resource server and authenticates by presenting the access token.

(F) The resource server validates the access token, and if valid, serves the request.

Example explanation

Authorized login of third-party applications: When APP or webpage accesses some third-party applications, the user will be required to log in to another cooperative platform, such as QQ, Weibo, and WeChat authorized login.

Native app authorization: App login request background interface. For security authentication, all requests carry token information. If login verification, request background data.

Front-end and back-end separation single-page application (spa): Front-end and back-end separation framework, the front-end requests back-end data, and requires oauth2 security authentication, such as apps developed using vue, react or h5.

Client authorization mode The
client must be authorized by the user (authorization grant) in order to obtain an access token. OAuth 2.0 defines four authorization methods:

Authorization code mode (authorization code)
simplified mode (implicit)
password mode (resource owner password credentials)
client mode (client credentials)
four authorization modes

Authorization code mode

The authorization code model is the authorization model with the most complete functions and the most rigorous process.

(1) When the user accesses the client, the latter directs the former to the authentication server. Assuming that the user is authorized, the authentication server directs the user to the "redirection URI" specified in advance by the client and attaches an authorization code.

(2) The client receives the authorization code, attaches the previous "redirect URI", and applies for a token from the authentication server: GET /oauth/token?response_type=code&client_id=test&redirect_uri=redirect page link. The code authorization code is returned after the request is successful. The general valid time is 10 minutes.

(3) The authentication server checks the authorization code and redirect URI, and after confirming that they are correct, sends an access token and a refresh token to the client. POST /oauth/token?response_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=Redirect page link. The request successfully returns access Token and refresh Token.

The following are the parameters required for the above steps.

In step A, the URI that the client applies for authentication includes the following parameters:

  • response_type: indicates the authorization type, a required option, the value here is fixed as "code"

  • client_id: indicates the ID of the client, a required option

  • redirect_uri: indicates the redirection URI, optional

  • scope: Indicates the scope of authority applied for, optional

  • state: Represents the current state of the client. Any value can be specified, and the authentication server will return this value intact.

Below is an example.

GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com

In step C, the server responds to the client's URI, including the following parameters:

  • code: indicates the authorization code, a required option. The validity period of the code should be very short, usually set to 10 minutes, the client can only use the code once, otherwise it will be rejected by the authorization server. This code has a one-to-one correspondence with the client ID and redirection URI.

  • state: If the client request contains this parameter, the response of the authentication server must also contain this parameter exactly.

Below is an example.

HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz

In step D, the HTTP request for the client to apply for a token to the authentication server includes the following parameters:

  • grant_type: indicates the authorization mode used, a required option, the value here is fixed as "authorization_code".

  • code: indicates the authorization code obtained in the previous step, a required option.

  • redirect_uri: indicates the redirection URI, which is mandatory and must be consistent with the parameter value in step A.

  • client_id: indicates the client ID, a required option.

Below is an example.

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
 
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

In step E, the HTTP response sent by the authentication server contains the following parameters:

  • access_token: indicates an access token, a required option.

  • token_type: Indicates the token type. This value is case-insensitive and is a required option. It can be bearer or mac.

  • expires_in: Indicates the expiration time, in seconds. If this parameter is omitted, the expiration time must be set in other ways.

  • refresh_token: indicates the refresh token, used to obtain the next access token, optional.

  • scope: Indicates the scope of authority. If it is consistent with the scope applied by the client, this item can be omitted.

Below is an example.


     HTTP/1.1 200 OK
     Content-Type: application/json;charset=UTF-8
     Cache-Control: no-store
     Pragma: no-cache

     {
       "access_token":"2YotnFZFEjr1zCsicMWpAA",
       "token_type":"example",
       "expires_in":3600,
       "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
       "example_parameter":"example_value"
     }

As you can see from the code above, the relevant parameters are sent in JSON format (Content-Type: application/json). In addition, the HTTP header information clearly specifies that it must not be cached.

Reference

https://oauth.net/2/
The OAuth 2.0 Authorization Framework:
http://www.rfcreader.com/#rfc6749
https://tools.ietf.org/html/rfc6749
http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
https://developers.google.com/identity/protocols/oauth2


Kotlin Developer Community

Focus on sharing Java, Kotlin, Spring/Spring Boot, MySQL, redis, neo4j, NoSQL, Android, JavaScript, React, Node, functional programming, programming ideas, "high availability, high performance, high real-time" large-scale distributed system architecture design theme.

High availability, high performance, high real-time large-scale distributed system architecture design

Distributed framework: Zookeeper, distributed middleware framework, etc.
Distributed storage: GridFS, FastDFS, TFS, MemCache, redis and other
distributed databases: Cobar, tddl, Amoeba, Mycat
cloud computing, big data, AI algorithm
virtualization, cloud native Technology
Distributed computing framework: MapReduce, Hadoop, Storm, Flink and other
distributed communication mechanisms: Dubbo, RPC calls, shared remote data, message queues and other
message queues MQ: Kafka, MetaQ, RocketMQ
How to build a highly available system: Based on hardware and software Realization of some typical solutions such as middleware and system architecture: HAProxy, Corosync+Pacemaker-based high-availability cluster suite middleware system
Mycat architecture distributed evolution
problems behind big data Join: contradictions and reconciliation of data, network, memory and computing capabilities
High-performance problems in Java distributed systems: AIO, NIO, Netty or self-developed frameworks?
High-performance event dispatch mechanism: thread pool model, Disruptor model, etc. . .

The embracing wood is born at the end of the mill; the nine-story platform starts from the basement; the journey of a thousand miles begins with a single step. If you don't accumulate steps, you can't reach a thousand miles; if you don't accumulate small streams, you can't become a river.

Introduction to Kotlin

Kotlin is a non-research language. It is a very pragmatic industrial-grade programming language. Its mission is to help programmers solve problems in actual engineering practice. Using Kotlin makes the lives of Java programmers better. The null pointer errors in Java, the lengthy boilerplate code that wastes time, the verbose syntax restrictions, etc., all disappear in Kotlin. Kotlin is simple and pragmatic, with concise and powerful syntax, safe and expressive, and extremely productive.

Java was born in 1995 and has a history of 23 years. The current latest version is Java 9. In the process of continuous development and prosperity of the JVM ecosystem, brother languages ​​such as Scala, Groovy, and Clojure were also born.

Kotlin is also an excellent member of the JVM family. Kotlin is a modern language (version 1.0 was released in February 2016). Its original purpose is to optimize the defects of the Java language like Scala, provide simpler and more practical programming language features, and solve performance problems, such as compilation time. JetBrains has done a great job in these areas.

Features of Kotlin language

After developing in Java for many years, it's great to be able to try something new. If you are a Java developer, Kotlin will be very natural and smooth. If you are a Swift developer, you will feel familiar, such as Nullability. Features of Kotlin language are:

1. Concise

Significantly reduce the amount of boilerplate code.

2. 100% interoperability with Java

Kotlin can directly interact with Java classes and vice versa. This feature allows us to directly reuse our code base and migrate it to Kotlin. Because Java's interoperability is almost everywhere. We can directly access platform APIs and existing code bases, while still enjoying and using all the powerful modern language features of Kotlin.

3. Extension function

Kotlin is similar to C# and Gosu in that it provides the ability to provide new functional extensions for existing classes without having to inherit from the class or use any type of design patterns (such as decorator patterns).

4. Functional programming

The Kotlin language first supports functional programming, just like Scala. It has basic functional features such as high-order functions and lambda expressions.

5. Default and named parameters

In Kotlin, you can set a default value for the parameters in a function and give each parameter a name. This helps to write easy-to-read code.

6. Powerful development tool support

And because it is produced by JetBrains, we have great IDE support. Although the automatic conversion from Java to Kotlin is not 100% OK, it is indeed a very good tool. When using IDEA's tools to convert Java code to Kotlin code, 60%-70% of the resulting code can be reused easily, and the cost of modification is small.

In addition to simple and powerful syntax features, Kotlin also has a very practical API and an ecosystem built around it. For example: collection API, IO extension, reflection API, etc. At the same time, the Kotlin community also provides a wealth of documents and a lot of learning materials, as well as online REPL.

A modern programming language that makes developers happier. Open source forever

Picture from "Kotlin from entry to advanced combat" (Chen Guangjian, Tsinghua University Press)

Picture from "Kotlin from entry to advanced combat" (Chen Guangjian, Tsinghua University Press)

https://kotlinlang.org/

Guess you like

Origin blog.csdn.net/universsky2015/article/details/109302482