Authentication and authentication
What is authentication and authorization
1. Authentication
User authentication is to verify the identity of the user. It solves the problem of who I am. It is the process of obtaining user information from user request information. Authentication is a process.
For example ๐ฐ : when you log in, enter the user name and password, the system determines whether your user name and password are in the existing user and gives the result feedback, this process is user authentication.
User authentication includes user name and password login, verification code for mobile phone and email, and third-party login.
2. Authorization
User authorization is to grant permissions to users for subsequent access and operations. It solves the “I can do those things” problem. It is the process from obtaining user information to granting user permissions.
For example ๐ฐ : take the elevator every day swipe card, swipe card process is authorized, granted us access to so-and-so level of authority. It’s the process by which someone or an organization gives someone the authority to do something.
certification | authorization |
---|---|
Authentication confirms your identity to grant access to the system | Authorization determines whether you have access to a resource |
This is the process of validating user credentials to gain user access | This is the process of verifying that access is allowed |
It determines whether the user is who he claims to be | It determines what users can and cannot access |
Authentication usually requires a user name and password | Authentication factors required for authorization may vary, depending on the level of security |
Authentication is the first step in authorization, and therefore always the first step. | Authorization is completed after successful authentication. |
What is Cookie and Session
credentials
The premise of realizing authentication and authorization is to need a kind of media (certificate) ** to mark the identity of the visitor, and this media (certificate) is the certificate
In Internet applications, it is common that after logging in, the server issues a token to the user’s browser. This token identifies you, and the browser carries this token every time it sends a request.
1, Cookie,
- HTTP is a stateless protocol (for the transaction without memory, each time the client and the server session is complete, the server will not save any session information) : each request is completely independent, the server can’t confirm the identity of visitors to the current information, unable to distinguish between the last request of the sender and the sender is not the same person at this time. So in order for the server and browser to do session tracking (to know who is visiting me), they must actively maintain a state that tells the server whether the previous two requests came from the same browser. This state needs to be implemented through cookies or sessions.
- ** Cookie stored on the client: ** Cookie is a small piece of data that the server sends to the user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server.
- ** Cookies are not cross-domain: ** Each cookie is bound to a single domain name, which cannot be obtained and used under other domain names. First-level domain names and second-level domain names are allowed to be shared (depending on domain).
2, the Session
When we use cookies, the server actually gives a pass-through certificate to the client visiting it, and whoever accesses it must bring his pass-through certificate. This allows the server to verify the customer’s identity from the access certificate. That’s how cookies work
Cookies can make the server program track each client access, but each client access must return these cookies, if there are a lot of cookies, this will increase the amount of data transmission between the client and the server, thus the birth of Session to solve this problem.
The principle of Session is that when the same client interacts with the server, it does not need to return all the Cookie values each time. Instead, it only needs to return an ID, which is generated when the client accesses the server for the first time, and each client is unique. This gives each client a unique ID that the client simply needs to return.
When the program needs to create a session for a client request, the server first checks whether the client request contains a session id. If the client request contains a sessionID, it indicates that the client has created a session before. If the client request does not contain a sessionID, create a session for the client and claim a sessionID associated with the session.
The value of the sessionID should be a string that is neither repetitive nor easy to find a pattern to fake (the server creates it automatically), and the sessionID will be returned to the client for storage in this response.
3. The difference between cookies and sessions
- ** Security: ** Sessions are more secure than cookies, which are stored on the server and on the client.
- The value types are different: Cookies only support string data. If you want to set other types of data, you need to convert them into strings. Session can store any data type.
- **Cookie can be set to hold for a long time. For example, the default login function we often use, the Session expiration time is generally short, and the client is closed (by default) or the Session timeout will be invalid.
- ** Different storage sizes: ** The data saved by a single Cookie cannot exceed 4K, and the data stored by a Session is much higher than that of cookies. However, too many visits will occupy too many server resources.
What is Token
Token is an authentication certificate that needs to be carried when accessing server resources
Simple token composition: userID(used to identify a unique user)+time(timestamp of the current time)+sign(signature, the first bits of the token are hashed into a hexadecimal string of a certain length)
Validation process
- The client requests login using the username and password
- The server receives a request to verify the user name and password
- After the authentication succeeds, the server issues a token and sends the token to the client
- After receiving the token, the client stores it, for example, in a cookie or localStorage
- Each time a client requests resources from the server, it must carry a token signed by the server
- The server receives the request and verifies the token in the request. If the verification succeeds, it returns the requested data to the client
- Each request needs to carry the token, which needs to be put in the HTTP Header
- Token-based user authentication is a stateless authentication mode on the server. The server does not need to store token data. The computation time of token parsing is used to exchange the storage space of session, thus reducing the pressure on the server and reducing the frequent query of the database
- The token is completely managed by the application, so it can bypass the same-origin policy
The difference between Token and Session
- Session is a mechanism for recording the Session status between the server and the client. The server is stateful and can record Session information. Tokens are tokens, resource credentials needed to access resource interfaces (apis). Token makes the server stateless and does not store session information.
- Session and Token are not contradictory. As an authentication Token, Session security is better than Session security, because each request has a signature and can prevent listening and replay attacks, while Session must rely on the link layer to ensure communication security. If you need to implement stateful sessions, you can still add sessions to store some state on the server side.
- Session authentication is simply storing User information in the Session. Because of the unpredictability of the SessionID, it is considered safe for the time being. Tokens, if referred to as OAuth tokens or similar mechanisms, provide authentication and authorization, authentication for the user and authorization for the App. The goal is to give an App access to a user’s information. The Token here is unique. It cannot be transferred to other apps, nor can it be transferred to other users. Session provides only a simple authentication, that is, as long as the SessionID is present, the User is considered to have full rights. This data should only be kept on the site and should not be shared with other websites or third-party apps. So to put it simply: If your user data may need to be shared with a third party, or allow a third party to call an API, use Token. If it’s always just your own website, your own App, it doesn’t matter what you use.
What is JWT
JWT: JSON Web Token. Suitable for distributed authorization mode. It is the most popular cross-domain authentication solution
After the user logs in successfully, the authentication server returns a JWT with signed authentication. The JWT is stored on the client (such as a browser or APP). Each time the client accesses the application server, the JWT is added to the HEADER Authorization field of HTTP.
Authorization: Bearer <token>
Copy the code
Different from centralized Session management, JWT contains user information. Each application server can independently determine which user JWT is, whether it is valid, and whether it is expired. There is no need to confirm with the authentication server, and there is no Session synchronization problem. JWT contains at least the following information:
- Sub: Subject, usually a user ID.
- Exp: Expiration Time. Expiration time.
- Signature: the signature. Used to verify that the JWT is valid.
The client receives the JWT returned by the server, which can be stored in cookies or localStorage.
The use of JWT
1. Add a token to the Authorization of the request header during the request
2. You can add the token field to the URL
3. It can also be placed in the request body of a Post request when it crosses domains
Practice is the only way to test truth
1. Cookie practice
Set format: this.ctx.cookies. Set (key,value,options)
Get (key) : this.ctx.cookies.
This.ctx.cookies. Get (key,{encrypt: true})
Clear format: this.ctx.cookies. Set (key,null)
/ / set
this.ctx.cookies.set('auth'.'test', {
maxAge: 24 * 3600 * 1000.// The expiration time is 1 day
httpOnly: true.signed: true.// Sign cookies to prevent them from being modified
encrypt: true.// Encrypt the cookie. If the cookie is encrypted, it needs to be decrypted at the time of acquisition
});
/ / to get
this.ctx.cookies.get('auth', {encrypt: true}
/ / remove
this.ctx.cookies.set('auth'.null}
Copy the code
Options parameter maxAge: Sets the maximum duration of the key-value pair in the browser. Is the number of milliseconds from the current time of the server. Expires: Sets an expiration time for this key-value pair. If maxAge is set, expires will be overwritten. If maxAge and Expires are not set, cookies will expire when the browser’s session expires (usually when the browser is closed). Path: Sets the effective URL path of the key-value pair. The default setting is on the root path (/), that is, all urls under the current domain name can access this Cookie. Domain: specifies the domain name for which the key pair takes effect. By default, the domain name is not configured and can be accessed only in the specified domain name. HttpOnly: sets whether key/value pairs can be accessed by JS. Default is true. Js is not allowed to access key/value pairs. Secure: The Settings are only transmitted over HTTPS connections. The framework helps us determine whether secure is currently automatically set over HTTPS connections. In addition to these attributes, the framework extends support for three additional parameters:
Overwrite: Sets the handling of key-value pairs with the same key. If true, the last value overwrites the previous one, otherwise two set-cookie headers will be sent. Signed: indicates whether to sign cookies. If the value is set to true, the value of the key-value pair will be signed at the same time when the key-value pair is set, and the value will be checked when the key-value pair is fetched to prevent the front-end from tampering with the value. The default is true. Encrypt: Specifies whether to encrypt the Cookie. If this parameter is set to true, the value of the key pair is encrypted before sending the Cookie. The client cannot read the plaintext value of the Cookie. The default is false.
Let’s use Node to write three interfaces
router.get('/api/user/setauth', controller.user.SetAuth);
router.get('/api/user/auth', _Cookie, controller.user.Auth);
router.get('/api/user/clearauth', _Cookie, controller.user.ClearAuth);
// _Cookie is a middleware that verifies cookies and blocks requests without cookies
Copy the code
public async SetAuth() {
this.ctx.cookies.set('auth'.'test', {
maxAge: 24 * 3600 * 1000.// The expiration time is 1 day
httpOnly: true.signed: true.// Sign cookies to prevent them from being modified
encrypt: true.// Encrypt the cookie. If the cookie is encrypted, it needs to be decrypted at the time of acquisition
});
this.ctx.body = { message: 'Cookie set successful'.code: 200 };
}
public async Auth() {
// cookie
const cookie = this.ctx.cookies.get('auth', { encrypt: true });
this.ctx.body = { message: 'The cookie just set is:${cookie}`.code: 200 };
}
public async ClearAuth() {
// cookie
this.ctx.cookies.set('auth'.null);
this.ctx.body = { message: 'Cookie cleared successfully'.code: 200 };
}
Copy the code
We first request/API /user/setauth to set the cookie
We then request ยท/ API/USet /auth to view the cookie we just set
We then request/API /user/clearauth to clear the set cookie
Finally we request/API /user/auth again and this time the request will be intercepted by the middleware
2. Session practice
Set the format: this.ctx.session.[key]=value
Access format: this.ctx.cookies.[key]
// Set session you can set multiple data types
this.ctx.session.auth = 'test';
/ / to get
const sessionvalue = this.ctx.session.auth
// Many configurations for configuring sessions are similar to cookies
config.session = {
// Set the key in session cookis
key: 'SESSION_KEY'.// Set the expiration time
maxAge: 24 * 3600 * 1000.httpOnly: true.// Set whether to encrypt
encrypt: true.// Set whether the session is delayed every time the page is refreshed
renew: true};Copy the code
We’ll still use Node to write both interfaces
router.get('/api/user/setsession', controller.user.setSession);
router.get('/api/user/session', controller.user.getSession);
Copy the code
public async setSession() {
this.ctx.session.auth = 'test';
this.ctx.body = { message: 'Session setup succeeded'.code: 200 };
}
public async getSession() {
const session = this.ctx.session.auth;
this.ctx.body = { message: 'The session I just set is:${session}`.code: 200 };
}
Copy the code
Let’s call/API /user/ setSession and see that session has been set successfully
Next we call/API /user/session to get the session we just generated
As you can see, we can get the session value and SESSION_KEY has been written into the requested cookie
3. JWT practice
Set format: app.jwt.sign(options,sectet)
App.jwt. verify(token,sectet)
Different frameworks have different Settings
/ / set
const token = app.jwt.sign({
userid,
exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60), // The token is valid for 24 hours
// exp: math.floor (date.now () / 1000) + 10, // test -- token valid for 10 seconds
}, app.config.jwt.secret,);
// Decrypt fetch
const tokenvalue = ctx.app.jwt.verify(token, secret);
Copy the code
We still use Node to write both interfaces
router.post('/api/user/login', controller.user.Login);
router.post('/api/user/getUserInfo', _jwt, controller.user.GetUserInfo);
// _jwt is the middleware that validates tokens
import { Context } from 'egg';
const consola = require('consola');
const JwtCheck = (secret: string) = > {
return async (ctx: Context, next: any) => {
const token = ctx.request.header.authorization as string; / / get the token
let decode = ' ';
if(token ! = ='null' && token) {
try {
const formatToken = token.split(' ') [1];
/ / decryption token
decode = ctx.app.jwt.verify(formatToken, secret);
ctx.decode = decode;
await next();
} catch (error) {
consola.error(error);
if (error.name === 'TokenExpiredError') {
consola.info('Token expired! ');
ctx.body = {
msg: 'Token has expired, please log in again'.code: 401};return;
}
ctx.body = {
msg: 'Token is invalid, please log in again'.code: 401};return; }}else {
ctx.body = {
code: 401.msg: 'Token does not exist'};return; }}; };export default JwtCheck;
Copy the code
public async Login() {
const { ctx, app } = this;
const { userid } = ctx.request.body;
consola.log('userid', userid);
/ / token is generated
const token = app.jwt.sign({
userid,
exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60), // The token is valid for 24 hours
// exp: math.floor (date.now () / 1000) + 10, // test -- token valid for 10 seconds
}, app.config.jwt.secret);
ctx.body = { message: 'Login successful! '.code: 1.data: { token } };
}
// Get user information
public async GetUserInfo() {
const ctx = this.ctx;
ctx.body = { message: 'Succeeded. The user ID of the login user is:${ctx.decode.userid}`.code: 1 };
}
Copy the code
First we set the token by calling the/API /user/login login interface
Then we call the interface/API /user/getUserInfo to determine the validity of the token and get the userID
Remember to add Bearer to the Authorization field in the request header
You can see our login userid ๐
Refer to the article: www.cnblogs.com/xosg/p/1025…
Segmentfault.com/a/119000002…
Blog.csdn.net/jnshu_it/ar…