Home >headlines >[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

青灯夜游
青灯夜游forward
2022-08-23 19:27:548402browse

Regarding front-end authentication, what do Token, Cookie, Session, JWT, single sign-on, scan code login, and one-click login mean? What are the functions of each? How do you usually do it? And how do you store it? So how do you keep it safe? The following article will teach you how to handle all authentication schemes on the front and back ends, so that you will no longer be confused!

I still remember that during the interview, an interviewer asked, regarding front-end authentication, what Token, Cookie, Session, JWT, Single Sign-on are? what's the effect? How do you usually do it? And how do you store it? So how do you ensure the safety of it?

After a series of questions, I was so anxious and overwhelmed that I couldn’t speak...

In fact, there are many methods of authentication, as follows I have summarized 10 commonly used authentication methods, so which one is the most suitable for your system? Which one is the safest? Then let us slowly explore and find the answer from the following ~

What will you learn through this article?

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confusedBefore introducing the authentication method, we first need to understand:

What is authentication, authorization, authentication, permission control

and With them as the foundation, we can have a thorough understanding of the relationship between them from beginning to end~

What is certification?

Authentication (Identification)

refers to confirming the identity of the declarant based on the declarant’s unique identification information. The vernacular means:

You need to use your ID card to prove that you are yourself

. For example, our common authentication technology:

ID card
  • User name and password
  • User mobile phone: mobile phone text message, mobile phone QR code scanning , Gesture password
  • User’s email address
  • User’s biological characteristics: fingerprint, voice, eye iris
  • User’s big data identification
  • , etc.
What is authorization?

Authorization

: In the field of information security, it refers to the resource owner delegating executor and giving execution Or specifies the range of resource operation permissions to facilitate related operations on resources.

In the field of real life, for example:

Bank cards (distributed by the bank), access cards (distributed by the property management office), keys (distributed by the landlord), these are all authorized in real life way of implementation.

In the Internet field, for example:

The session mechanism of the web server, the cookie mechanism of the web browser, and the issuance of authorization tokens (tokens) are all authorization mechanisms.

What is authentication?

Authentication(Authentication)

In the field of information security, it refers to identifying and confirming the authenticity of the identity rights declared by a declarant. process. If you start from authorization, it will be easier to understand authentication. Authorization and authentication are two matching upstream and downstream relationships.

Authorization first, then authentication

.

In the field of real life:

The access control card needs to pass the access card identifier, and the bank card needs to pass the bank card identifier;

In the Internet field:

Verify the legality and validity of session/cookie/token

Authentication

is a link between the previous and the next. The upstream accepts the authorized output, verifies its authenticity, and then Obtain permission, which will prepare you for the next step of permission control.

What is permission control?

Permission Control (Access/Permission Control)

Define executable operations as a permission list, and then determine whether the operation is allowed/forbiddenFor permission control, It can be understood in two parts: one is permissions and the other is control. Permission is an abstract logical concept, while control is a concrete implementation method.

In the field of real life:

Take the implementation of access control card permissions as an example. An access control card has the permission to open all doors in the company; an access control card has the permission of the administrator role. , so you can open all doors in the company.

In the Internet field:

Use the web backend service to control interface access and allow or deny access requests.

What is the relationship between authentication, authorization, authentication and permission control?

Seeing this, we should understand

Authentication

, Authorization, Authentication and Permission Control These four links are a relationship that occurs in sequence , upstream and downstream ;

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confusedIt should be noted that these four Links sometimes occur simultaneously. For example, in the following scenarios:

  • Use the access card to open the door: The four links of authentication, authorization, authentication, and permission control are completed in one go, happening simultaneously in an instant
  • User's website login: When a user logs in using a username and password, authentication and authorization are completed together, while authentication and permission control occur in subsequent access requests, such as when selecting items or making payments.

Here is a small question for everyone to think about: What is the relationship between authentication and authentication? Everyone is welcome to discuss in the comment area

Now that we have understood the relationship between them, we should talk about front-end authentication? And what are the differences between them?

1. HTTP Basic Authentication


In HTTP, Basic Access Authentication) is to allow the client ( Usually refers to the web browser) when making a request, the user's identity is verified by the user providing the user name and password.

Because almost all online websites do not use this certification scheme, everyone can understand the scheme

1.1 Authentication flow chart

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

1.2 Authentication step analysis

  • Client (such as browser): Request a restricted list data or resource from the server, for example, the fields are as follows

     GET /list/ HTTP/1.1
     Host: www.baidu.com
     Authorization: Basic aHR0cHdhdGNoOmY=
  • Server: Hello client, this resource is in the security zone baidu.com. It is a restricted resource and requires basic authentication;

    and returns 401 to the client. Status code (Unauthorized) and an authentication domain provided www-Authenticate: Basic realm=”baidu.com”requires authentication;

    whereBasic is the verification mode, and realm="baidu.com" indicates that the client needs to enter the username and password of this security domain, not those of other domains

     HTTP/1.1 401 Unauthorized
     www-Authenticate: Basic realm= "baidu.com"
  • Client: Server, I have given you the username and password, please take a look; (Note: If the client is a browser, a pop-up window will automatically pop up at this time to let you know The user enters the username and password);

    After entering the username and password, the client sends the username and password to the server in Base64 encryption.

    The transmission format is as follows (Basic content is :Username:ase64 form of password):

     GET /list/ HTTP/1.1 
     Authorization: Basic Ksid2FuZzp3YW5n==
  • ##Server: Hello client, I have verified it Your username and password in the Authorization fields are correct. This is the resource you want.

     HTTP/1.1 200 OK
     ...

1.3 Advantages

Simple, basically supported by all popular browsers

1.4 Disadvantages

  • Unsafe:

      Because it is based on HTTP transmission, It's almost naked on the Internet, and although it uses Base64 to encode, this encoding can be easily decoded.
    • Even if the authentication content cannot be decoded into the original username and password, it is unsafe. A malicious user can obtain the authentication content and use it to continuously share the server to initiate requests. This is the so-called replay attack.
  • Unable to actively log out:

      Since the HTTP protocol does not provide a mechanism to clear the Basic authentication information in the browser, unless The tab or browser is closed, or the user clears history.

1.5 Usage scenarios

Internal network, or a network that does not have very high security requirements.

2. Session-Cookie Authentication


Session-Cookie Authentication uses the Session (session) of the server and the browser ( Client) Cookie to implement the front-end and back-end communication authentication mode.

Before understanding this sentence, let’s briefly understand

What is Cookie and What is Session?

2.1 What is Cookie

As we all know,

HTTP is a stateless protocol (no memory capacity for transaction processing, Each time the session between the client and the server is completed, the server will not save any session information);

So in order for the server to distinguish between different clients, it must actively maintain a state, which is used for Inform the server whether the two requests before and after are from the same browser. This state can be achieved through

Cookie.

Features:

  • Cookies are stored on the client side and can be tampered with at will. They are not safe.
  • There is a size limit, the maximum is 4kb
  • There is a quantity limit. Generally, a browser can only No more than 20 cookies can be stored, and browsers generally only allow 300 cookies.
  • Android and IOS do not support cookies well
  • Cookies are not cross-domain, but first-level domain names and second-level domain names are not supported. Level domain names are allowed for shared use (depending on domain)

2.2 What is Session

The abstract concept of Session is session , is an abstraction of the interaction between the user and the server in order to achieve interruption/continuation operations during the stateless protocol communication process;

Specifically, it is a Session structure generated by the server, which can Saved in a variety of ways, such as memory, database, files, etc. Large websites generally have dedicated Session server clusters to save user sessions;

Principle process:

  • Client: The user sends a request to the server for the first time;

  • Server: Receives the data and automatically creates it for the user Specific Session/Session ID to identify the user and track the user's current session process;

  • Client: The browser receives the response to obtain the session information, and will Bring Session/Session ID with the next request;

  • #Server: After extraction, the server will compare it with the locally saved Session ID to find the session of the specific user. Then obtain the session status;

  • At this point, the communication between the client and the server becomes stateful communication;

Features:

  • Session is saved on the server;
  • is performed through the server’s own encryption protocol;

Differences from Cookies:

  • Security: Cookies are stored on the client side and can be tampered with at will, while Sessions are stored on the server side and cannot be forged, so Session security is higher;
  • Different types of access values: Cookie only supports string data, Session can store any data type;
  • Different validity periods: Cookie can be set In order to maintain it for a long time, Session generally has a shorter expiration time;
  • The storage size is different: The data saved by the cookie cannot exceed 4K;

See Some students here may have thought, does Session-Cookie just store Session in the client’s Cookie?

Bingo, that’s indeed the case, let’s look down below

2.3 Session-Cookie authentication flow chart

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

##2.4 Session-Cookie authentication step analysis

  • Client: Send login information username/password to the server to request login verification;

  • Server: Verify login information, verification passed Then automatically create a Session (save the Session in memory or in Redis), and then generate a unique identification string session identity credential for this Session session_id (commonly called sid), and set this unique identifier in the response header Set-Cookie;

    Note: You can use a signature to encrypt

    sid, The server will decrypt based on the corresponding secret key (optional step)

  • Client: Received from the server After the response, the response header will be parsed and sid will be automatically saved in the local cookie. The browser will automatically attach the cookie information under the domain name to the request header in the next HTTP request;

  • Server: When receiving a client request, it will parse the sid in the request header Cookie, and then use this sid to find the one saved by the server. sid of the client, and then determine whether the request is legal;

##2.5 Advantages of Session-Cookie

Cookie is simple and easy to use
  • Session data is stored on the server side, which is more convenient to manage than JWT. That is, when the user logs in and actively logs out, he only needs to add and delete the corresponding Session. It is convenient for management
  • Only back-end operations are required, and the front-end can be operated without any sense;

2.6 Disadvantages of Session-Cookie

  • Depends on Cookies. Once the user disables Cookies on the browser, it will be GG Smecta;
  • It is very unsafe. Cookies expose data in the browser, increasing the risk of data theft. Risk (easily attacked by CSRF, etc.);
  • Session is stored on the server side, which increases the overhead of the server side. When the number of users is large, the server performance will be greatly reduced;
  • Support for mobile terminals Sexually unfriendly;

2.7 Usage scenarios

  • Generally applicable to medium and large websites (except mobile APP) ;
  • Since general Sessions need to be stored centrally on a memory server (such as Redis), this will increase the server's budget, so if the budget is not enough, please choose carefully;

2.8 Recommended Session libraries commonly used on the front end

3. Token authentication


Now we have learned that Session-Cookie Some shortcomings and Session maintenance cause great trouble to the server. We must find a place to store it, consider distribution issues, and even enable a separate Redis cluster for it. Is there a better way?

ThenToken came into being

3.1 What is Token

Token is a token. When the client accesses the server, the server will issue a token to it after passing the verification. After that, the client can bring the token to access the server. The server Just verify the validity of the token.

Summary in one sentence;Resource credentials required when accessing the resource interface (API)

General Token composition:

uid (The user’s unique identity) time (The timestamp of the current time) sign (Signature, the first few digits of the Token are compressed into A hexadecimal string of a certain length)

Token authentication flow chart:

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

Token authentication steps Analysis:

  • ##Client: Enter user name and password to request login verification;

  • Server: After receiving the request, verify the user name and password; after successful verification, the server will issue a Token and send the Token to the client;

  • Client: After receiving the Token, it needs to be stored. The web side usually stores it in localStorage or Cookie, and the mobile native APP usually stores it in the local cache;

  • The client sends a request: When requesting API resources from the server, the Token is sent to the server through the HTTP request header Authorization field or other methods;

  • Server: Receive the request, and then verify the Token contained in the client request. If the verification is successful, the requested data will be returned to the client, otherwise the return will be refused (401);

Advantages of Token:

  • # The server is stateless and has good scalability: The Token mechanism does not need to store sessions on the server side ( Session) information, because the Token itself contains information related to the user it identifies, which is conducive to sharing user status among multiple services
  • Supports APP mobile devices;
  • Good security: Effectively avoid CSRF attacks (because no cookies are required)
  • Support cross-program calls: Because cookies do not allow cross-domain access, and Token does not have this problem

Disadvantages of Token:

  • Coordination: Requires front-end and back-end cooperation;
  • Bandwidth occupied: Under normal circumstances, it is larger than sid, consuming more traffic and occupying more bandwidth
  • Performance issues: Although there is no need to access the database or remote service for permission verification when verifying the Token, operations such as encryption and decryption of the Token are required, so it will consume more performance;
  • Short validity period: In order to avoid Token has been stolen. Generally, the validity period of Token will be set shorter, so there is Refresh Token;

3.2 What is Refresh Token? )

The Token used for authentication by the business interface, we call it

Access Token.

For security reasons, the validity period of our

Access Token is generally set to be shorter to avoid being stolen. However, a too short validity period will cause Access Token to expire frequently. What should I do after expiration?

One way is:

Refresh the Access Token and let the user log in again to obtain a new Token, which will be very troublesome;

另外一种办法是:再来一个 Token,一个专门生成 Access Token 的 Token,我们称为 Refresh Token

  • Access Token: 用来访问业务接口,由于有效期足够短,盗用风险小,也可以使请求方式更宽松灵活;
  • Refresh Token: 用来获取 Access Token,有效期可以长一些,通过独立服务和严格的请求方式增加安全性;由于不常验证,也可以如前面的 Session 一样处理;

Refresh Token 的认证流程图:

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

Refresh Token 认证步骤解析:

  • 客户端: 输入用户名和密码请求登录校验;

  • 服务端: 收到请求,验证用户名与密码;验证成功后,服务端会签发一个 Access TokenRefresh Token 并返回给客户端;

  • 客户端:Access TokenRefresh Token 存储在本地;

  • 客户端发送请求: 请求数据时,携带 Access Token 传输给服务端;

  • 服务端:

    • 验证 Access Token 有效:正常返回数据
    • 验证 Access Token 过期:拒绝请求
  • 客户端 ( Access Token 已过期) 则重新传输 Refresh Token 给服务端;

  • 服务端 ( Access Token 已过期) 验证 Refresh Token ,验证成功后返回新的 Access Token 给客户端;

  • 客户端: 重新携带新的 Access Token 请求接口;

3.3 Token 和 Session-Cookie 的区别

Session-CookieToken 有很多类似的地方,但是 Token 更像是 Session-Cookie 的升级改良版。

  • 存储地不同: Session 一般是存储在服务端;Token 是无状态的,一般由前端存储;
  • 安全性不同: Session 和 Token 并不矛盾,作为身份认证 Token 安全性比 Session 好,因为每一个请求都有签名还能防止监听以及重放攻击;
  • 支持性不同: Session-Cookie 认证需要靠浏览器的 Cookie 机制实现,如果遇到原生 NativeAPP 时这种机制就不起作用了,或是浏览器的 Cookie 存储功能被禁用,也是无法使用该认证机制实现鉴权的;而 Token 验证机制丰富了客户端类型。

如果你的用户数据可能需要和第三方共享,或者允许第三方调用 API 接口,用 Token 。如果永远只是自己的网站,自己的 App,用什么就无所谓了。

4. JWT(JSON Web Token)鉴权


通过第三节,我们知道了 Token 的使用方式以及组成,我们不难发现,服务端验证客户端发送过来的 Token 时,还需要查询数据库获取用户基本信息,然后验证 Token 是否有效;

这样每次请求验证都要查询数据库,增加了查库带来的延迟等性能消耗;

那么这时候业界常用的 JWT 就应运而生了!!!

4.1 什么是 JWT

JWTAuth0 提出的通过 对 JSON 进行加密签名来实现授权验证的方案;

就是登录成功后将相关用户信息组成 JSON 对象,然后对这个对象进行某种方式的加密,返回给客户端; 客户端在下次请求时带上这个 Token; 服务端再收到请求时校验 token 合法性,其实也就是在校验请求的合法性。

4.2 JWT 的组成

JWT 由三部分组成: Header 头部Payload 负载Signature 签名

它是一个很长的字符串,中间用点(.)分隔成三个部分。列如 :

 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Header 头部:

在 Header 中通常包含了两部分:

  • typ:代表 Token 的类型,这里使用的是 JWT 类型;
  • alg:使用的 Hash 算法,例如 HMAC SHA256 或 RSA.
 {
   "alg": "HS256",
   "typ": "JWT"
 }

Payload 负载:

它包含一些声明 Claim (实体的描述,通常是一个 User 信息,还包括一些其他的元数据) ,用来存放实际需要传递的数据,JWT 规定了7个官方字段:

  • iss (issuer):签发人
  • exp (expiration time):过期时间
  • sub (subject):主题
  • aud (audience):受众
  • nbf (Not Before):生效时间
  • iat (Issued At):签发时间
  • jti (JWT ID):编号

除了官方字段,你还可以在这个部分定义私有字段,下面就是一个例子。

 {
   "sub": "1234567890",
   "name": "John Doe",
   "admin": true
 }

Signature 签名

Signature 部分是对前两部分的签名,防止数据篡改。

首先,需要指定一个密钥(secret)。这个密钥只有服务器才知道,不能泄露给用户。然后,使用 Header 里面指定的签名算法(默认是 HMAC SHA256),按照下面的公式产生签名。

 HMACSHA256(
   base64UrlEncode(header) + "." +
   base64UrlEncode(payload),
   secret)

4.3 JWT 的使用方式

客户端收到服务器返回的 JWT,可以储存在 Cookie 里面,也可以储存在 localStorage。

此后,客户端每次与服务器通信,都要带上这个 JWT。你可以把它放在 Cookie 里面自动发送,但是这样不能跨域,所以更好的做法是放在 HTTP 请求的头信息Authorization字段里面。

 Authorization: Bearer <token></token>

4.4 JWT 的认证流程图

其实 JWT 的认证流程与 Token 的认证流程差不多,只是不需要再单独去查询数据库查找用户用户;简要概括如下:

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

4.5 JWT 的优点

  • 不需要在服务端保存会话信息(RESTful API 的原则之一就是无状态),所以易于应用的扩展,即信息不保存在服务端,不会存在 Session 扩展不方便的情况;
  • JWT 中的 Payload 负载可以存储常用信息,用于信息交换,有效地使用 JWT,可以降低服务端查询数据库的次数

4.6 JWT 的缺点

  • 加密问题: JWT 默认是不加密,但也是可以加密的。生成原始 Token 以后,可以用密钥再加密一次。
  • 到期问题: 由于服务器不保存 Session 状态,因此无法在使用过程中废止某个 Token,或者更改 Token 的权限。也就是说,一旦 JWT 签发了,在到期之前就会始终有效,除非服务器部署额外的逻辑。

4.7 前端常用的 JWT 库推荐

5. 单点登录(Single Sign On)


前面我们已经知道了,在同域下的客户端/服务端认证系统中,通过客户端携带凭证,可以维持一段时间内的登录状态。

但随着企业的发展,一个大型系统里可能包含 n 多子系统,用户在操作不同的系统时,需要多次登录,很麻烦,那么单点登录(SSO) 就可以很好的解决这个问题的,在多个应用系统中,只需要登录一次,就可以访问其他相互信任的应用系统。

  • 例如登录天猫,淘宝也会自动登录;
  • 登录百度贴吧,百度网盘也会自动登录;

5.1 同域下的 SSO(主域名相同)

当百度网站存在两个相同主域名下的贴吧子系统 tieba.baidu.com 和网盘子系统 pan.baidu.com 时,以下为他们实现 SSO 的步骤:

  • 客户端: 用户访问某个子系统时(例如 tieba.baidu.com),如果没有登录,则跳转至 SSO 认证中心提供的登录页面进行登录;

  • 服务端: 登录认证后,服务端把登录用户的信息存储于 Session 中,并且附加在响应头的 Set-Cookie 字段中,设置 Cookie 的 Domain 为 .baidu.com

  • 客户端:再次发送请求时,携带主域名 Domain 下的 Cookie 给服务器,此时服务端就可以通过该 Cookie 来验证登录状态了;

其实我们不难发现,这就是我们上面讲的 Session-Cookie 认证 登录方式; 但如果是不同域呢?毕竟不同域之间 Cookie 是不共享的,那怎么办?

5.2 跨域下的 SSO(主域名不同)

In our common shopping websites Tmall (tmall.com) and Taobao (taobao.com), we only need to log in to one of the systems, and the other system will log in by default after opening it. So how do we do this? Woolen cloth?

Then there is CAS (Central Authentication Service) central authorization service, so let’s first talk about the process of CAS;

CAS authentication flow chart under single sign-on:

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

Detailed explanation of CAS authentication steps under single sign-on:

  • Client: Started accessing system A;

  • System A: Found that the user is not logged in, redirected to CAS authentication service (sso.com). At the same time, the URL address parameter carries a page link that will jump back to system A after successful login (sso.com/login?redir…

  • CAS authentication service: It is found that the request cookie does not carry the login ticket certificate (TGC), so the CAS authentication service determines that the user is in the not logged in state, and redirects the user page to CAS. Login interface, users log in on the CAS login page.

  • Client: Enter the username and password for CAS system authentication;

  • CAS authentication service: Verify user information, and generate TGC into your own Session, and write the Domain as in the form of Set-Cookie Under the domain of sso.com; at the same time, a authorization token ST (Service Ticket) is generated, and then redirected to the address of system A. The redirected address contains the generated ST (redirect address :www.taobao.com?token=ST-345678)

  • System A: Send a request to the CAS authentication service with ST. The CAS authentication service verifies the validity of the ticket (ST). After successful verification, System A knows that the user has logged in to CAS (the ST can be saved in Cookie or locally), and the System A server uses the ticket (ST) to create a certificate with the user. The session, called a partial session, returns protected resources;

At this point the client can happily communicate with System A~

  • Client: Started accessing system B;

  • System B: Found that the user is not logged in, redirected to SSO authentication service, and pass your own address as a parameter, and attach the cookie value under the sso.com domain is the TGC generated in the fifth step;

  • CAS authentication Service: The CAS authentication service center finds that the user has logged in, jumps back to the address of system B, and attaches the ticket (ST);

  • System B: Get the ticket (ST) and go to the CAS authentication service to verify the validity of the ticket (ST). After the verification is successful, the client can also interact with System B~

(PS: It feels a bit scumbag to have two boats~)

Points to note under single sign-on:

  • As shown in the process in the figure, we found that CAS Authentication Service is issuing After the authorization token ST is redirected directly, it is actually easier to be stolen. Then we need to successfully authenticate to CAS in system A or system B (steps 14 and 14 in the figure) After step 11), generate another new verification Token and return it to the client for storage;

  • CAS generally provides four interfaces:

    • /login: Login interface, used to log in to the central authorization service
    • /logout: Logout interface, used to log out from the central authorization service
    • /validate: Used to verify whether the user has logged in to the central authorization service
    • /serviceValidate: Used to allow each Service to verify whether the user has logged in to the central authorization service
  • Ticket generated by CAS:

    • TGT (Ticket Grangting Ticket): TGT is a Login ticket# issued by CAS for the user ##, with TGT, users can prove that they have successfully logged in to CAS.
    • TGC: Ticket Granting Cookie: CAS Server generates TGT and puts it into its own Session, and TGC is the unique identifier (SessionId) of this Session, which is placed on the browser in the form of a Cookie. It is the credential used by CAS Server to identify the user.
    • ST (Service Ticket): ST is a ticket issued by CAS for the user to access a Service.

6. OAuth 2.0


When we actually browse the website, when we log in, in addition to entering the current In addition to the website account and password, we also found that you can log in through third-party QQ or WeChat, so how to do this, we have to talk about

OAuth.

OAuth 协议又有 1.0 和 2.0 两个版本,2.0 版整个授权验证流程更简单更安全,也是目前最主要的用户身份验证和授权方式。

6.1 什么是 OAuth 2.0?

OAuth 是一个开放标准,允许用户授权第三方网站 (CSDN、思否等) 访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方网站;

常见的提供 OAuth 认证服务的厂商: 支付宝、QQ、微信、微博

简单说,OAuth 就是一种授权机制。数据的所有者告诉系统,同意授权第三方应用进入系统,获取这些数据。系统从而产生一个短期的进入令牌(Token),用来代替密码,供第三方应用使用。

令牌与密码的差异:

令牌(Token)密码(Password) 的作用是一样的,都可以进入系统,但是有三点差异。

  • 令牌是短期的,到期会自动失效: 用户自己无法修改。密码一般长期有效,用户不修改,就不会发生变化。

  • 令牌可以被数据所有者撤销,会立即失效。

  • 令牌有权限范围(scope): 对于网络服务来说,只读令牌就比读写令牌更安全。密码一般是完整权限。

OAuth 2.0 对于如何颁发令牌的细节,规定得非常详细。具体来说,一共分成四种授权模式 (Authorization Grant) ,适用于不同的互联网场景。

无论哪个模式都拥有三个必要角色:客户端授权服务器资源服务器,有的还有用户(资源拥有者),下面简单介绍下四种授权模式。

6.2 授权码模式

授权码(Authorization Code Grant) 方式,指的是第三方应用先申请一个授权码,然后再用该码获取令牌。

这种方式是最常用的流程,安全性也最高,它适用于那些有后端服务的 Web 应用。授权码通过前端传送,令牌则是储存在后端,而且所有与资源服务器的通信都在后端完成。这样的前后端分离,可以避免令牌泄漏。

一句话概括:客户端换取授权码,客户端使用授权码换token,客户端使用token访问资源

授权码模式的步骤详解

  • 客户端:

    打开网站 A,点击登录按钮,请求 A 服务,A 服务重定向 (重定向地址如下) 至授权服务器 (如QQ、微信授权服务)。

     https://qq.com/oauth/authorize?
       response_type=code&
       client_id=CLIENT_ID&
       redirect_uri=CALLBACK_URL&
       scope=read

    上面 URL 中,response_type 参数表示要求返回授权码(code),client_id 参数让 B 知道是谁在请求,redirect_uri 参数是 B 接受或拒绝请求后的跳转网址,scope 参数表示要求的授权范围(这里是只读)

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

  • 授权服务器:

    授权服务网站 会要求用户登录,然后询问是否同意给予 A 网站授权。用户表示同意,这时授权服务网站 就会跳回 redirect_uri 参数指定的网址。跳转时,会传回一个授权码,就像下面这样。

    https://a.com/callback?code=AUTHORIZATION_CODE

    上面 URL 中,code 参数就是授权码。

[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

  • 网站 A 服务器:

    拿到授权码以后,就可以向 授权服务器 (qq.com) 请求令牌,请求地址如下:

     https://qq.com/oauth/token?
      client_id=CLIENT_ID&
      client_secret=CLIENT_SECRET&
      grant_type=authorization_code&
      code=AUTHORIZATION_CODE&
      redirect_uri=CALLBACK_URL

    上面 URL 中,client_id 参数和 client_secret 参数用来让授权服务器 确认 A 的身份(client_secret 参数是保密的,因此只能在后端发请求),grant_type参数的值是AUTHORIZATION_CODE,表示采用的授权方式是授权码,code 参数是上一步拿到的授权码,redirect_uri 参数是令牌颁发后的回调网址。

1[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

  • 授权服务器:

    收到请求以后,验证通过,就会颁发令牌。具体做法是向 redirect_uri 指定的网址,发送一段 JSON 数据。

     {    
       "access_token":"ACCESS_TOKEN",
       "token_type":"bearer",
       "expires_in":2592000,
       "refresh_token":"REFRESH_TOKEN",
       "scope":"read",
       "uid":100101,
       "info":{...}
     }

    上面 JSON 数据中,access_token 字段就是令牌,A 网站在后端拿到了,然后返回给客户端即可。

1[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

6.3 隐藏式模式(Implicit Grant)

有些 Web 应用是纯前端应用,没有后端。这时就不能用上面的方式了,必须将令牌储存在前端。OAuth2.0 就规定了第二种方式,允许直接向前端颁发令牌。这种方式没有授权码这个中间步骤,所以称为(授权码)"隐藏式"(implicit)。

一句话概括:客户端让用户登录授权服务器换token,客户端使用token访问资源

隐藏式模式的步骤详解

  • 客户端:

    打开网站 A,A 网站提供一个链接,要求用户跳转到 授权服务器,授权用户数据给 A 网站使用。如下链接:

     https://qq.com/oauth/authorize?
       response_type=token&
       client_id=CLIENT_ID&
       redirect_uri=CALLBACK_URL&
       scope=read

    上面 URL 中,response_type参数为token,表示要求直接返回令牌。

  • 授权服务器:

    用户跳转到授权服务器,登录后同意给予 A 网站授权。这时,授权服务器就会跳回redirect_uri 参数指定的跳转网址,并且把令牌作为 URL 参数,传给 A 网站。

     https://a.com/callback#token=ACCESS_TOKEN

    上面 URL 中,token参数就是令牌,A 网站因此直接在前端拿到令牌。

1[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

注意:

  • 令牌的位置是 URL 锚点(fragment),而不是查询字符串(querystring),这是因为 OAuth 2.0 允许跳转网址是 HTTP 协议,因此存在"中间人攻击"的风险,而浏览器跳转时,锚点不会发到服务器,就减少了泄漏令牌的风险。

  • 这种方式把令牌直接传给前端,是很不安全的。因此,只能用于一些安全要求不高的场景,并且令牌的有效期必须非常短,通常就是会话期间(session)有效,浏览器关掉,令牌就失效了。

6.4 用户名密码式模式(Password Credentials Grant)

如果你高度信任某个应用,OAuth 2.0 也允许用户把用户名和密码,直接告诉该应用。该应用就使用你的密码,申请令牌,这种方式称为"密码式"(password)。

一句话概括:用户在客户端提交账号密码换token,客户端使用token访问资源。

密码式模式的步骤详解

  • 客户端:

    A 网站要求用户提供 授权服务器(qq.com) 的用户名和密码。拿到以后,A 就直接向 授权服务器 请求令牌。

     https://oauth.b.com/token?
       grant_type=password&
       username=USERNAME&
       password=PASSWORD&
       client_id=CLIENT_ID

    上面 URL 中,grant_type参数是授权方式,这里的password表示"密码式",usernamepassword授权服务器 的用户名和密码。

  • 授权服务器:

    授权服务器 验证身份通过后,直接给出令牌。

    注意,这时不需要跳转,而是把令牌放在 JSON 数据里面,作为 HTTP 回应,A 网站因此拿到令牌。

这种方式需要用户给出自己的用户名/密码,显然风险很大,因此只适用于其他授权方式都无法采用的情况,而且必须是用户高度信任的应用。

6.5 客户端模式(Client Credentials Grant)

客户端模式指客户端以自己的名义,而不是以用户的名义,向授权服务器 进行认证。

主要适用于没有前端的命令行应用。

一句话概括:客户端使用自己的标识换token,客户端使用token访问资源

客户端模式的步骤详解

  • 客户端:

    客户端向授权服务器 进行身份认证,并要求一个访问令牌。请求链接地址:

     https://oauth.b.com/token?
       grant_type=client_credentials&
       client_id=CLIENT_ID&
       client_secret=CLIENT_SECRET

    上面 URL 中,grant_type参数等于client_credentials表示采用凭证式,client_idclient_secret用来让授权服务器 确认 A 的身份。

  • 授权服务器:

    授权服务器 验证通过以后,直接返回令牌。

注意:这种方式给出的令牌,是针对第三方应用的,而不是针对用户的,即有可能多个用户共享同一个令牌。

6.5 授权模式选型

按授权需要的多端情况:

模式 需要前端 需要后端 需要用户响应 需要客户端密钥
授权码模式 Authorization Code
隐式授权模式 Implicit Grant
密码授权模式 Password Grant
客户端授权模式 Client Credentials

Classified according to client type and access token owner:

1[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

The above are mainly simple. The basic logic of OAuth2.0 is explained. If you want to learn more in detail, you can view the official document OAuth or RFC 6749; you can also view the OAuth 2.0 concept and authorization process summary Compare

7. Federated login and trusted login


##7.1 What is joint login

Joint login refers to a login service that includes multiple credential verifications at the same time. At the same time, it can also be understood as a login service that uses third-party credentials for verification.

In layman terms: For two websites A and B, use the account and password of website B when logging in to website A, which is a joint login, or use website A when logging in to website B. The account password is also a joint login.

This concept is actually similar to the

username password mode authentication method of OAuth2.0 mentioned above.

The most classic is the use scenario of embedded H5 in APP. When the user enters the embedded H5 from the APP, we hope that the logged-in user in the APP can access the restricted resources in H5 without Login users need to log in to access.

There are two main ideas here. One is to attach the login token to the URL parameter when jumping to the embedded H5 page natively. The other is to embed H5 actively through formulating with the native client. The protocol to obtain the login status within the application.

7.2 What is trust login

Trust login refers to all logins that do not require the user’s active participation, such as establishing In the binding relationship between private devices and users, the credentials are the information of the private devices, and the user does not need to provide additional credentials at this time. Trusted login also refers to using a third-party, relatively mature user library to verify credentials and log in to the website you are currently visiting.

In layman terms: When website A is logged in, you can jump directly to website B without logging in, which is trust login.

Currently, the more common third-party trusted login accounts are: QQ Taobao account, Alipay account, Weibo account, etc.

It is not difficult for us to find that OAtuth 2.0 is actually the epitome of trust login, because it is with OAuth that our trust login can be realized.

8. Unique login


—Suppose the product manager now makes a request:

I want to realize that users can only log in on one device. Users are prohibited from logging in repeatedly;

- As excellent programmers, of course we will satisfy him! !

8.1 What is unique login

Unique login refers to

prohibiting multiple people from logging into the same account at the same time. The latter login behavior will cause the former to go offline.

To put it simply: After account A logs in on computer A, account A logs in again using computer B. When computer A requests the page, it prompts "Restart" Login" information and jump to the login page

8.2 Unique login flow chart

1[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

8.3 Detailed explanation of the unique login steps

User operation on client A:

  • Enter account request Login interface;

  • The backend generates the corresponding Token and returns it to client A, and saves a login status on the server;

  • Client A saves the Token, and each request carries the corresponding Token in the header;

The user operates on client B:

Suddenly When the user starts the login operation on client B, we will find that the steps are almost the same as the operation on client A;

It’s just that when the backend generates a new Token, it must first verify the login status. Then generate the corresponding new Token;

9. Scan the QR code to log in


##9.1 What is QR code login

Scan QR code login is usually found in mobile APPs. Many PC websites provide the function of QR code login. There is no need to enter any account number and password on the web page. You only need to allow mobile APPs (such as WeChat, Taobao, QQ, etc.) etc.) The logged-in user actively scans the QR code and then confirms the login. The way to quickly log in to the same application on the PC is to Scan the QR code to log in.

9.2 What is QR code

QR code Also known as QR code, common QR code QR Code, the full name of QR is Quick Response, which is a very popular encoding method on mobile devices in recent years. It can store more information and represent more data types than the traditional Bar Code.

Through the above, we can easily find that scanning the QR code to log in requires three terminals (PC terminal, Mobile terminal, Server terminal) Only by cooperation can the successful login be achieved;

9.3 Authentication flow chart for scanning QR code to log in

1[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

9.4 Detailed explanation of the steps to scan the QR code to log in (the stage to be scanned, the stage to be confirmed, and the confirmed stage)

Stage to be scanned:

  • PC side:

    Open a website (such as taobao.com) or an APP (such as WeChat) and scan the QR code to log in entrance; it will carry the device information of the PC and send a request to obtain the QR code to the server;

  • Server:

    The server receives After receiving the request, a UUID is randomly generated as the QR code ID, and the UUID is associated with the PC side device information and stored in the Redis server, and then returned to the PC side; at the same time, an expiration time is set. Afterwards, the user needs to refresh the QR code to log in and obtain it again.

  • PC side:

    After receiving the QR code ID, convert the QR code ID into the form of QR code Display and wait for the mobile terminal to scan the code. And at this time, the PC starts polling to check the QR code status until the login is successful.

    If the mobile terminal is not scanned, the QR code will automatically expire after a period of time.

Scanned code and pending confirmation:

  • Mobile version:

    Open the APP (WeChat or Taobao, etc.) corresponding to that you have logged into on the mobile phone, and start scanning to identify the QR code displayed on the PC;

    After scanning the QR code on the mobile phone, it will automatically Obtain the QR code ID, and send the mobile terminal login information voucher (Token) and QR code ID as parameters to the server. At this time, the mobile phone must be logged in (the prerequisite for using scan login is that the mobile terminal application is logged in status, so that the login status can be shared).

  • Server:

    After receiving the request from the mobile phone, it will Token and the QR code ID Association, why do we need to associate it? Because when we use WeChat and log out on the mobile side, the PC side should also log out. This association plays this role. Then a temporary Token will be generated, which will be returned to the mobile terminal, and the one-time Token will be used as a voucher for confirmation.

Confirmed stage:

  • Mobile version:

    Receive After receiving the confirmation information, click the confirmation button, and the mobile terminal will carry the temporary Token obtained in the previous step and send it to the server for verification;

  • server:

    After the server side verification is completed, the QR code status will be updated and a formal Token will be generated for the PC side. Subsequently, the PC side will hold this Token to access the server side. .

  • PC side:

    Polling shows that the QR code status is logged in, and the generated Token is obtained, and the login is completed. Subsequent access is completed based on Token.

10. One-click login (applicable to native APP)


10.1 Login with account and password

As we all know, the most traditional login method is to log in with account and password, simple and crude, generally there will be no problems;

Disadvantages:

  • But this method requires users to remember themselves The account number and password have a memory cost. In order to reduce memory costs, users are likely to use the same set of account passwords on different platforms. From a security perspective, once the account password of a certain platform is leaked, other platforms used by the user will be affected.

  • In addition, since the account has nothing to do with personal identity, it means that the same user can register multiple different accounts, which means malicious registration may occur.

Until the mandatory real-name system for mobile phone cards was solved!

10.2 Mobile phone number verification code login

With the development of wireless Internet and the promotion of mobile phone card real-name system, mobile phone number has become a special identity certificate. Compared with account passwords, mobile phone numbers can better verify the user's identity and prevent malicious registration.

However, registering a mobile phone number still requires a series of tedious operations: enter the mobile phone number, wait for the SMS verification code, enter the verification code, and click to log in. The whole process takes at least twenty seconds, and if you don't receive the text message, you have to log in to make up for it. This kind of problem may lead to potential user loss.

From a security perspective, there is also the risk of verification code leakage. If someone knows your mobile phone number and steals the verification code, he can also log in to your account.

So there is a one-click login operation!

10.3 What is one-click login

Let’s think about it, why do we need a verification code? The function of the verification code is to confirm that the mobile phone number is yours. In addition to using text messages, is there any other way to authenticate the mobile phone number?

So, our protagonist can log in with one click.

The function of the SMS verification code is to prove that the user on the current operation page and the user who entered the mobile phone number are the same person. In fact, as long as we can obtain the mobile phone card number used by the current mobile phone, we can directly use this number to log in. , no additional operations are required, this is One-click login.

Whether one-click login can be done depends on whether the operator opens related services; as the operator opens related services, we are now able to access the SDK provided by the operator and pay to use related services.

One-click login flow chart:

1[Summary sharing] 10 commonly used front-end and back-end authentication methods, so you will no longer be confused

Detailed explanation of one-click login steps:

  • SDK initialization: Call the SDK method and pass in the AppKey and AppSecret configured by the platform

  • Revoke the authorization page: Call the SDK to invoke the authorization interface. The SDK will first initiate a request to the operator to obtain the mobile phone number mask. After the request is successful, it will jump to the authorization page. The authorization page will display the mobile phone number mask and operator agreement for user confirmation.

  • Agree to the authorization and log in: The user agrees to the relevant agreement and clicks the login button on the authorization page. The SDK will request the Token for this time. After the request is successful, the Token Return to the client

  • Get the number: Send the obtained Token to its own server, and the server will carry the Token and call the operator's one-click login interface. If the call is successful, the mobile phone number will be returned. The server uses the mobile phone number to log in or register, and returns the operation results to the client to complete one-click login.

Three major operators’ open platforms:

  • ##Mobile-Internet capability open platform

  • Telecom-Tianyi Account Open Platform

  • ##China Unicom-WO Open Platform

    Since the three major domestic operators each have independent SDKs, the compatibility work will be particularly cumbersome. If you want to use a one-click login solution, you may wish to use a third party to provide number authentication services. The following suppliers all have mobile phone number authentication capabilities:

      Alibaba-Number Authentication Service
    • Chuanglan-Flash Verification
    • Aurora-Aurora Certification
    • mob-Second Verification
Note:

During the authentication process, the user is required to turn on the cellular network. If the mobile phone device does not have a SIM card inserted, or the cellular network is turned off In the case of network, authentication cannot be completed. Therefore, even if one-click login is enabled, it still needs to be compatible with traditional login methods, allowing users to still complete the login process normally in the event of failure.

Summary

After learning and understanding the above 10 authentication methods, let’s briefly summarize

  • HTTP Basic Authentication Suitable for internal networks, or networks that do not have very high security requirements;
  • Session-Cookie Suitable for general medium and large-scale websites (except mobile APP);
  • Token and JWT are suitable for most enterprise websites on the market, and JWT performance will be better than Token;
  • Single sign-on Suitable for large enterprise websites with many subsystems;
  • OAuth 2.0 Suitable for websites that need to quickly register users;
  • Scan QR code to log in Applicable to enterprises that have completed the deployment of three terminals;
  • One-click login Applicable to native APP;

This article is reproduced from: https://juejin.cn/post/7129298214959710244

Author: Master Yi

(Learning video sharing: web front-end )

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete