Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
36 views2 pages

OAuth 2

The document explains the differences between authentication and authorization, highlighting that authentication verifies identity while authorization determines access permissions. It also discusses cookies and sessions, detailing their roles in tracking user identity and state, and introduces token-based authentication using JWT, which enhances scalability by eliminating the need for server-side session storage. Additionally, it covers OAuth 2.0 as an authorization protocol and addresses common issues with token authentication, such as token invalidation and renewal strategies.

Uploaded by

Ashihs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views2 pages

OAuth 2

The document explains the differences between authentication and authorization, highlighting that authentication verifies identity while authorization determines access permissions. It also discusses cookies and sessions, detailing their roles in tracking user identity and state, and introduces token-based authentication using JWT, which enhances scalability by eliminating the need for server-side session storage. Additionally, it covers OAuth 2.0 as an authorization protocol and addresses common issues with token authentication, such as token invalidation and renewal strategies.

Uploaded by

Ashihs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

What is the difference between Authentication and Cookie data is stored on the client (browser side), and session data is
stored on the server side. Relatively speaking, Session security is
Authorization?
higher. If some sensitive information using cookies is not written in
This is a question that most people will confuse. First of all, you will recognize
these two nouns from the pronunciation. Many people will confuse their cookies, it is best to encrypt the cookie information and then use the
pronunciation, so I suggest that you first check how to read these two words server to decrypt it when it is used.
and what their specific meanings are. So, how to use Session for authentication?
To put it simply: Many times we use SessionID to achieve a specific user. SessionID is usually
Authentication: Who are you? stored in Redis. For example: The user successfully logs in to the system, and
Authorization: What do you have permission to do. then returns a cookie with the SessionID to the client. When the user makes
A slightly more formal (puppet) statement is: a request to the backend, the SessionID will be brought on, so that the
Authentication is the credential (such as username / user ID and password) that verifies backend knows your identity status. The detailed process of this
your identity. With this credential, the system knows that you are you, that is, the user authentication method is as follows:
exists in the system. Therefore, Authentication is called identity / user authentication. The user sends a username and password to the server for logging in to the system.
Authorization occurs after Authentication . Authorization, you should understand just After the server passes the authentication, the server creates a session for the user and
by looking at the meaning, it mainly controls our access to the system. For example, stores the session information.
some specific resources can only be accessed by people with specific permissions, such The server returns a SessionID to the user and writes the user's cookie.
as admin, and some operations on system resources, such as deleting, adding, and When the user remains logged in, cookies are sent with each subsequent request.
updating, can only be performed by specific talents. The server can compare the Session ID stored on the cookie with the Session
These two are generally used together in our system in order to protect the information stored in memory or in the database to verify the user's identity, and when
security of our system. the response information is returned to the user client, the current state of the user is
attached.
2. What are cookies? What are the functions of cookies? 4. What is Token? What is JWT? How to authenticate
How to use cookies on the server? based on Token?
2.1 What is a cookie? What does a cookie do? In the previous question, we explored the use of Session to authenticate
Cookies and Session are both session methods used to track the identity of a users, and gave several Spring Session case studies. We know that Session
browser user, but their application scenarios are different. information needs to be saved on the server side. This method will bring
Wikipedia defines cookies as follows: Cookies are data (usually encrypted) some troubles, such as requiring us to guarantee the availability of the
that some websites store on a user's local terminal in order to identify the session information server, not suitable for mobile terminals (depending on
user. In simple terms: Cookies are stored on the client and are generally cookies), and so on.
used to store user information . Is there a way to achieve authentication without storing Session information
Here are some use cases for cookies: yourself? Just use Token! JWT (JSON Web Token) is the implementation of
We save the information of users who have logged in in cookies. The next time you visit this method. In this way, the server does not need to save the session data. It
the website, the page can automatically fill in some basic information for you to log only needs to save the Token returned by the server to the client on the
in. In addition, cookies can save user preferences, themes and other setting information.
client, and the scalability is improved.
Use cookies to save sessions or tokens, and bring cookies when sending requests to the
backend so that the backend can get the session or token. This will record the current JWT is essentially a piece of signed JSON-formatted data. Because it is
state of the user, because the HTTP protocol is stateless. signed, the receiver can verify its authenticity.
Cookies can also be used to record and analyze user behavior. For a simple example, Here is a more formal definition of JWT from RFC 7519 .
when you shop online, because the HTTP protocol has no status, if the server wants to JSON Web Token (JWT) is a compact, URL-safe means of representing claims
get your stay status on a page or what products you have seen, a common
implementation is to store this information Cookies
to be transferred between two parties. The claims in a JWT are encoded as a
JSON object that is used as the payload of a JSON Web Signature (JWS)
2.2 How can I use cookies on the server? structure or as the plaintext of a JSON Web Encryption (JWE) structure,
1) Set the cookie back to the client enabling the claims to be digitally signed or integrity protected with a
@GetMapping ( " / change-username " )
public String setCookie ( HttpServletResponse response) { Message Authentication Code (MAC) and / or encrypted. ---- JSON Web
// Create a cookie Token (JWT)
Cookie cookie = new Cookie ( " username " , " Jovan " );
// Set cookie expiration time JWT consists of 3 parts:
cookie . SetMaxAge ( 7 * 24 * 60 * 60 ); // expires in 7 days Header: Metadata describing the JWT. Defines the algorithm for generating signatures
// add to and the type of Token.
response .addCookie (cookie);
Payload (load): used to store the actual data to be transferred
return " Username is changed! " ; Signature (Signed): server through Payload, Headerand a key ( secret) using a signature
} algorithm Header inside specified (the default is HMAC SHA256) is generated.
2) Use the @CookieValueannotations provided by the Spring framework In the application authentication based on the Token, the
to get the value of a specific cookie server Payload, Headerand a key ( secret) creates a token ( Token) and Tokensent
@GetMapping ( " / " ) to the client, the client will be Tokenstored in the Cookie or localStorage
public String readCookie ( @CookieValue ( value = " username " , which, after all requests sent by the client Will carry this token. You can put it
defaultValue = " Atta " ) String username) {
return " Hey! My username is " + username; inside Cookie sent automatically, but this can not be cross-domain, so a
} better approach is to put in the Authorization HTTP Header
3) Read all cookie values field: Authorization: Bearer Token.
@GetMapping ( " / all-cookies " )
public String readAllCookies ( HttpServletRequest request) {

Cookie [] cookies = request . GetCookies ();


if (cookies ! = Null ) {
return Arrays . Stream (cookies)
.map (C - > C . getName () + " = " + C . the getValue ())
. the collect ( Collectors . joining ( " , " ));
}

return " No cookies " ;


}
3. What is the difference between a cookie and a
The user sends a username and password to the server for logging in to the system.
session? How to use Session for authentication? The authentication service responded and returned a signed JWT with the content of
The main role of Session is to record the state of the user through the who the user was.
server. The typical scenario is a shopping cart. When you want to add an Every time the user sends a request to the backend, he will bring JWT in the header.
item to the shopping cart, the system does not know which user operated it The server checks the JWT and obtains user-related information from it.
because the HTTP protocol is stateless. After the server creates a specific 5 What is OAuth 2.0?
session for a specific user, it can identify this user and track this user.
OAuth is an industry standard authorization protocol that is mainly used to  Modify Secret : We create a dedicated key for each user. If we
authorize third-party applications to obtain limited permissions. OAuth 2.0 is want to invalidate a token, we can directly modify the key of the
a complete redesign of OAuth 1.0. OAuth 2.0 is faster and easier to corresponding user. However, this introduces greater harm than
implement. OAuth 1.0 has been abandoned. For more information, the introduction of the first two in-memory databases, such as:1⃣️If
see: rfc6749 . the service is distributed, the keys must be synchronized across
In fact, it is an authorization mechanism. Its ultimate purpose is to issue a multiple machines each time a new token is issued. To do this,
time-effective token token for third-party applications, so that third-party you need to store the secrets in a database or other external
applications can obtain related resources through the token. service so that it is not much different from session
OAuth 2.0 is more commonly used for third-party logins. When your website authentication.2⃣️If the user opens the system in two browsers at
is accessed by third-party logins, it is generally the OAuth 2.0 protocol used. the same time, or the system is also opened on the mobile phone,
if it logs out of the account from one place, it is necessary to log in
again elsewhere. This is not desirable.
 Keeping tokens short-lived and rotating frequently : a simple
Advantages of token authentication way. However, the login status of the user will not be persistently
recorded, and the user needs to log in frequently.

Stateless It is relatively easy to solve the problem that the token is still valid
after the password is changed. One way I think is better: use the hash
value of the user's password to sign the token. Therefore, if the
password is changed, any previous tokens will automatically fail to
The token itself contains all the information required for authentication,
verify.
so that our server does not need to store Session information, which
obviously increases the availability and scalability of the system and
greatly reduces the pressure on the server. However, due to the 2.token renewal issue
statelessness of the token, it also causes its biggest disadvantage: when
the backend discards a token or changes its permissions during the Generally, the token validity period is not recommended to be set too
validity period of the token, it will not take effect immediately. long, so how to authenticate after the token expires, and how to
Generally, it is necessary to wait until the validity period expires. In dynamically refresh the token to avoid users often needing to log in
addition, when the user logs out, the token is also valid. Unless, we add again?
extra processing logic to the backend.
Let's take a look at the general practice in session authentication: if
the session is valid for 30 minutes, if the user has access within 30
Token authentication common problems and solutions minutes, the session validity period is extended by 30 minutes.

1. Similar to the practice in Session authentication : this scheme is


1. Tokens are still valid in scenarios such as logout satisfactory for most scenarios. Assume that the validity period of
the token given by the server is 30 minutes. Each time the server
checks, if it finds that the validity period of the token is about to
Specific similar scenarios are: expire soon, the server will regenerate the token to the client. The
client checks the old and new tokens every time it requests, and if
1. sign out; they are not consistent, it updates the local token. The problem
with this approach is that the request will update the token only
2. change Password;
when it is about to expire, which is not very friendly to the client.
3. The server has modified the permissions or roles of a user;
2. Each request returns a new token : The idea of this scheme is
4. The user's account is deleted / suspended. simple, but it is obvious that the overhead will be relatively large.
5. The user is logged out by the administrator; 3. The validity period of the token is set to midnight : this scheme is a
compromise solution, which guarantees that most users can log in
This problem does not exist in the session authentication method, normally during the day and is suitable for systems with low
because in the session authentication method, the server can delete security requirements.
the corresponding session record. However, using token 4. User login returns two tokens : the first is acessToken, whose
authentication is not easy to solve. We also said that once the token is expiration time is the expiration time of the token itself, such as
sent, if the backend does not add other logic, it will be valid until it half an hour, and the other is refreshToken, which has a longer
expires. So how do we solve this problem? Checked a lot of expiration time, such as 1 day. After the client logs in, the
information and summarized the following schemes: accessToken and refreshToken are saved locally, and the
accessToken is passed to the server for each access. The server
checks the validity of the accessToken. If it expires, it passes the
 Store tokens in an in-memory database : Store tokens in a DB. refreshToken to the server. If it is valid, the server generates a
Redis in-memory databases are a good choice here. If you need to new accessToken to the client. Otherwise, the client can log in
invalidate a token, you can simply delete the token from again. The shortcomings of this program are:1⃣️Need client to
redis. However, this will lead to the step of querying the existence cooperate;2⃣️When the user logs out, it is necessary to ensure that
of the token from the DB each time a request is sent using the both tokens are invalid;3⃣️During the process of re-requesting the
token, and it violates the principle of statelessness of the JWT. token, the token may be temporarily unavailable (you can set a
timer on the client and when the accessToken is about to expire,
 Blacklisting mechanism : a way similar to the above, the use of in-
go ahead and obtain a new accessToken through refreshToken).
memory database such as redis maintain a blacklist, if you want a
token fails, then the token will be directly added to
the blacklist can be. Then, every time a token is used to make a
request, it will first determine whether the token exists in the
blacklist.

You might also like