Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

WEB verifies the relationship between jwt session cookie

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "relationship between WEB verification jwt session cookie", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "the relationship between WEB verification jwt session cookie" bar!

Web authentication is a basic function that any serious website must achieve. This feature solves the problem of letting the server "know you are you". This function may seem simple, but in fact it is full of holes. Because certification depends on the overall operation of a set of technologies, it is not enough to simply put some off-the-shelf technologies together. You must understand what each technology can do, what can't be done, and what problems can be solved in order to carefully design a set of authentication functions.

Two kinds of authentication

At present, there are two kinds of authentication methods on the market-- Session-based and Token-based.

The so-called Session-based authentication refers to storing a Session Id on the client side. When authenticating, the request carries the Session Id, and the server finds the corresponding Session from the Session data store. This approach is available in the framework of many websites.

The so-called Token-based authentication means that all authentication-related information is encoded into a Token on the server side and signed by the server to ensure that it will not be tampered with. Token itself is plaintext. The information stored in Token can be such as user id, permission list, user nickname and so on. In this way, the server can directly verify that the user's identity is legitimate as long as it holds the signatures of token and token. In reality, the main standard of Token-based authentication is Json Web Token (JWT), see RFC 7519.

Authentication mode

But I have to say that Token-based authentication is not very practical in reality.

JWT

A JWT looks something like this:

Base64 (header) .Base64 (json payload) .signature

The header section describes some basic information, such as what algorithm the token is signed with, what version it is, and so on.

Payload is a json object. You can place any information you want, as long as it conforms to the format of json. The standard already specifies the meaning of some fields, such as iat indicates the time when issue at,token was issued, exp indicates the time when token expires, and so on. According to these conventions, you can implement some small code bases to check whether token is out of date, and so on. Please note, however, that many people misunderstand that JWT is encrypted, but payload is actually plaintext.

Signature is a signature. The server can choose an algorithm and a secret, splice it with payload and get a signature. Secret is not transmitted over the network, so the client cannot forge a JWT. In this way, once a signature is generated and passed back to the server, the server can know whether the token was originally generated or not.

Through this mechanism, some necessary information for authentication can be stored in JWT. Given a JWT, the server simply verifies:

This JWT's signature is correct.

The JWT is still in effect (that is, the current time is after the effective time of the JWT, before the expiration time)

The server can then trust the information contained in the JWT, including user id, contained permissions, and so on. The server does not need to query the user's information and the user's permission information again to respond to the request. No need for session, stateless Dafa is good! However, what needs to be splashed with cold water is:

With JWT, it is impossible to manage user requests on the server side-administrators cannot count how many individuals have logged in, how many times a person has logged in, and what device they have logged in; at the same time, they cannot forcibly "kick" off a user's login-once a JWT is generated, it is always valid before it expires. If you implement a function such as a token blacklist, it is equivalent to implementing the Session mechanism, and the benefits of statelessness are out of the question. This restriction is unacceptable to any website that wants to do serious user risk control.

Using JWT, the amount of data in payload can not be well controlled. Although the specification says that only authentication-related information should be put in the payload. But in fact, developers often misuse it and put almost all the data related to user into payload. The size of the payload is too large, such as reaching a few KB, it will greatly lose bandwidth and IO performance. Remember, in order to achieve statelessness, every request must carry a full amount of JWT.

These two serious defects limit the use of JWT to less serious scenarios. And for the real social, financial, games and other serious services, or to choose Session-based authentication.

Of course, signatures in token are good, because signatures ensure that token is indeed generated by the server and will not be tampered with. If user id is included in token, simple front-end error reporting can also be implemented; if there is also session id in token, Session-based authentication can be implemented on the server side. So, you can put several key data such as user id, session id, token expiration time into payload-just these, and no other data, to get a JWT for Session authentication. Further, if you slightly change the JWT specification, such as payload does not use JSON, but a more compact format; fixed signature algorithm, you can omit JWT's header; finally, optimize the coding format, you can get your own token.

But it doesn't matter whether you use session or token or any other name. What is important is that the server side must implement the session mechanism to facilitate the effective management of user login information.

Someone once told me a reason to use Token + stateless authentication: their storage is a cloud service and is charged by the number of calls. So they ask users to pass Token to the server every time, hoping to call that cloud service as little as possible. I am speechless about this.

How to store authentication information

After talking about session and token, let's talk about how this information is stored on the client side. Customers are also divided into two main categories-browsers and Native App. Let's start with the browser.

browser

The storage in browsers is mainly Local Storage and Cookie.

In fact, Session Storage is also used by browsers to store authentication information, but it is similar to Local Storage, but the failure mechanism is not the same. Only Local Storage is used here to discuss.

Developers who use Token-based certification like to use Header + Local Storage. Because this can effectively prevent CSRF (discussed in the next section).

However, the use of Local Storage will increase the chances of being recruited by XSS (Crossing Site Script). Once hit by XSS, the attacker can easily get the authentication information and send it back to his accepted URL without being noticed by the user. In this way, the attacker can easily log in instead of the user.

There is only one resource in the entire browser that cannot be accessed by the script. This is the cookie that is set to HttpOnly. This is an ideal place to put certified token/session id. To set this kind of token, you only need to write this when you Set Cookie:

Set-Cookie: access_token=xxxxxxxxxxxxxxxxxx; HttpOnly; Secure; Same-Site=strict; Path=/

What are Secure and Same-Site? Will be explained below)

There is no way for an XSS attacker to get your authentication information from HttpOnly's Cookie, unless he can access your computer directly after you log on to the website, open the browser's developer tool and copy and paste (tell you to leave the screen unlocked, huh).

Some people insist that their programs are protected from XSS attacks, so they can safely use Local Storage. For example, a program developed using the React framework theoretically all DOM nodes are generated by React's virtual DOM, and all tag generation is escape. A script dropped by espace cannot be executed, and it is impossible to XSS.

There's nothing wrong with this, but the biggest headache about XSS is that it's hard to make sure your site escape all users' input.

What you write is a website for writing articles, which needs to support users to enter HTML manually, and HTML must be displayed directly.

99% of the website you write is generated by a framework like React, but there may be some corners, so you still use traditional technologies such as jquery for convenience.

Your website is developed by a team. Although the development specification requires everyone to escape the user's input, as long as it is a person, it will be forgotten, and the matter of escape does not necessarily enter the Case list of the test.

……

As long as there is a loophole, the whole protection system will fail completely. This is why absolute isolation measures like HttpOnly Cookie are critical.

Native App

Native App is relatively simpler than browsers. Generally speaking, Native App is generated by static compilation, and there is no problem with XSS. At the same time, mobile operating systems will have a sandbox mechanism to prevent other App from reading their own data (unless you root. ). Therefore, Native App can safely store the data in an App sandbox. If you are worried, consider facilities such as iOS KeyChain or Android KeyStore.

But there are some differences between Native App and server interaction. Native App generally does not directly support the Cookie mechanism. So if a server uses Cookie to store authentication information, it requires Natvie App to parse Set-Cookie Header manually. At the same time, because Native App does not directly support Cookie, it tends to use AuthorizationHeader to pass in authentication information in the request. This also requires server adaptation. Of course, the easiest way is for Native App to introduce a library that simulates Cookie behavior.

Prevent CSRF

CSRF stands for Crossing Site Recource Forge. The approximate trigger process is:

The user logged in to site An and left the authentication information of site An in Cookie

The user enters site B, and site B lures the user to click in some way (such as a submission behavior is a form to a key interface on site A). When the user clicks, a request is sent to site A. The browser will attach the authentication information of site A to the request so that the request can be executed. This kind of behavior may be, but not limited to, giving rights / transfers / insults to some other user of an A site, and so on.

As mentioned above, many people use JWT+Local Storage to protect against CRSF. The reason for this is that the sending of Cookie is completely controlled by the browser, not by the web page itself. So the most simple and direct way is not to use Cookie, not to make it possible to send authentication information automatically. The problem is that there is a XSS risk in doing so. As you can see from the above, to avoid XSS, you must use HttpOnlyCookie.

So how can you guard against CSRF while using Cookie?

Traditional page Web website

In traditional page Web sites, CSRF Token is generally used. This is a very popular practice. Containers like Tomcat come with CSRF Token generation and check Filter.

This is how CSRF Token works. The client first requests a page with a submitted form from the server, and a CSRF Token is embedded in the page returned by the server. When the user submits the form, the CSRF Token is taken along and sent to the server for verification. So when the server sees the CSRF Token, it can boldly confirm that the user does see the pre-submission form interface, thus avoiding the possibility that the user will submit a forged form in a muddle.

SPA

CSRF Token is only suitable for traditional page requests, which can be embarrassing in the case of SPA.

In SPA, the interaction between the client and the server is mainly done through the interface, there is no concept of pages. At this point, you can do an interface to let the user get the CSRF Token, but you can't confirm anything. Because the attacker can call the same interface and get the legitimate CSRF Token.

There are several ways to do this:

Add a request secret to all interfaces to mark it as coming from a legitimate client. This secrect can be a fixed random string or it can be generated by some dynamic algorithm. For CSRF, browsers can only auto-pass Cookie, and can't help pass in secret. In this way, the risk of eliminating CSRF can be identified. Note, however, that this mechanism can only prevent CSRF, not man-made attacks. As long as the hacker gets the client, he is sure to find a way to generate secret.

One incidental feature of secret is to raise the bar for third-party users to call the interface at will-they have to look at the client source code and learn how to generate secret to call the interface.

Use Same-Site Cookie. Go back to the second step of the CSRF step above. When the user sees the forged form of site B, clicks submit, and sends a request to site A, the Cookie marked Same-Site=strict will not be carried, because the domain name B of the main site at that time is different from the domain name An of the submitted site. This is the Same-Site=strict tag is a relatively new standard. Most browsers already support it. But if a large number of users are still on old systems like IE8, this trick will not work.

Crooked tricks are always submitted in json format. A prerequisite for CSRF to occur is that it must be submitted with a traditional form. This is because traditional form submission can be cross-domain-if you are at site B, you can submit the form to site A. Ajax's request does not allow cross-domain unless CORS is enabled, so it naturally blocks this problem. The traditional form submission format must be application/x-www-form-urlencoded. Therefore, as long as you ensure that the server can refuse to process all POST requests in application/x-www-form-urlencoded format, you can ensure that SPA is not affected by CSRF. What do you use? JSON-application/json. The reason I specifically write this is that the default behavior of jquery's ajax library is to use the application/x-www-form-urlencoded format. If you are still using it, you can consider changing it. )

Another crooked trick, double certification. Put your authentication information on both HttpOnly Cookie and Authorization Header. The server needs to compare the two values to be the same before performing the authentication process. This protects against both XSS and CSRF. The price is that if your authentication information is long, some bandwidth will be wasted.

Always use https

During the online class in college, the teacher explained some of the principles of http and then gave us an assignment-go to the restaurant that offers WIFI and use a sniffer to pick up other people's passwords. Two weeks later, when we finished our homework, we were in a sad mood-the Nima Internet had been invented for more than a decade, without even the most basic protection.

Http is transmitted in clear text. Under http, any information entered by the user, every link node from his computer to the server is in clear text. Anywhere in this link, you can intercept the complete data, including your password, authentication token.

That's why https is necessary. Https provides three main guarantees:

End-to-end encryption. The raw data exchanged through https can only be seen by the user's browser and the final server. Other intermediate nodes cannot be obtained.

The client can determine that the server to be accessed is that server. This is supported by the certificate system. Once the certificate information of the URL appears in the browser's address bar, and it is prompted in green, then the user's mind can be secure. Of course, this is not entirely the case in China. If you talk too much about checking the water meter, those who understand it will understand it.

The server can determine that the accessed client is a legitimate client. This pattern is called "2-Way SSL" or "Mutal SSL". This mode is optional and requires the configuration of one more client certificate, which is not needed in general scenarios and is more common in enterprise Web services.

Earlier, many people had some resistance to https, generally because supporting https requires software modification; the server's cryptographic operations on certificates cost a lot of CPU; and bring more network requests and responses (more ssl handshakes). This will undoubtedly bring some cost and experience problems. But that was more than 10 years ago. Today's hardware and software processing capacity and network infrastructure are several times higher than they were 10 years ago. If today, a commercial website still insists on not using https, then its boss can be asked to run naked on the street.

After using https, for further security, set Cookie to Secure. In this way, browsers can carry Cookie only when they visit the https URL. If you do not make such a setting, the Cookie set through the https site will still be sent to the http site. When the domain name resolution of this site is hijacked, it may cause your authentication information to be sent to a fake server.

Authentication information should not be permanent

Many people choose to make a login permanent for the sake of "user experience". It is very dangerous to do so. Because once the user's authentication information is obtained by others, it will permanently lose the opportunity of defense (remember the consequences of leaving the computer screen unlocked? ).

Therefore, it is always necessary to ensure that the validity period of authentication information is limited. Generally, depending on the security level of the business scenario, it can be set to several minutes to several days. Even for social entertainment applications, it is best to be valid for no more than two weeks.

However, in order to improve the experience of frequently used users, you can consider implementing session renewal. However, it should be noted that the renewal here refers to the extension of the length of time for which the user does not need to log in, rather than directly lengthening the validity period of the session/token. Must be implemented to replace a new session id/token for the user. This can not only ensure that the same authentication information will not be valid forever, but also save normal and frequently used users from the pain of login.

To sum up.

To sum up, a reliable Web certification should:

You can use Session or Token for authentication, but always make sure that the server can manage Session and finally determine the validity of the authentication through the existence of Session.

Store the authentication information in the Cookie marked HttpOnly,Secure,Same-Site=strict, thus avoiding XSS and CSRF

Always use https, as long as your network link passes through the public network

If it is a traditional web site, please use the CSRF Token mechanism

If you can, do a simple request secret, which can help prevent CSRF or slightly raise the threshold for the interface to be crawled.

If it is a SPA application, feel free to disable application/x-www-form-urlencoded support boldly.

Guarantee that token/session must have a validity period

Thank you for your reading, the above is the content of "WEB verifies the relationship between jwt session cookie". After the study of this article, I believe you have a deeper understanding of the problem of WEB verifying the relationship between jwt session cookie. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report