Originally published on ISLAND

We left a little bit of a tail behind in the previous chapter, which was the permission validation middleware that didn’t have anything to play with, so it’s time to improve it today.

🍪 Cookies

How do you determine if the user is logged in? Cookie is a very good certificate, cookie will be reserved in the browser, each access request will carry, the backend through the cookie recognition, to determine whether the user login.

So, the first thing we want to do is save cookies when we log in. Modify the UserLogin code in userHandler

The cookie is added when the password is determined to be correct.

context.SetCookie("user_cookie".string(u.Id), 1000."/"."localhost".false.true)
Copy the code

Here are the parameters. The first parameter is the cookie name; The second argument is the cookie value; The third parameter is the cookie validity period. When the cookie exists for longer than the set time, the cookie will become invalid and it will no longer be a valid cookie. The fourth parameter is the directory in which the cookie resides; The fifth is the local field, indicating the scope of our cookie; The sixth indicates whether you can access only through HTTPS; The seventh indicates whether cookies can be manipulated by JS code.

Start our project, log in, F12 open our console, select Application, find cookies in the sidebar, and select our site, now you can see the cookie information we just set on the right side of us

In addition, there is the Expires/ max-age attribute, which indicates the expiration time of the cookie. Once the expiration time is exceeded, the cookie automatically disappears.

At this point, it indicates that our cookie was set successfully.

🥞 Obtains cookies from the middleware

Now that the cookie has been successful, it’s time to make changes to our newly written Auth middleware.

We’ll start by creating a 401.tmpl file to display information when our permissions are insufficient.

{{template "header"}} {{template "nav"}}<a href="/">Home page</a>
Copy the code

When we want to access a route that requires permissions, and we happen to lack them, we go to this page.

At this point we can refine our middleware.

func Auth(a) gin.HandlerFunc {
	return func(context *gin.Context) {
		_, e := context.Request.Cookie("user_cookie")
		if e == nil {
			context.Next()
		} else {
			context.Abort()
			context.HTML(http.StatusUnauthorized, "401.tmpl".nil)}}}Copy the code

Here we get the specified Cookie via context.request.cookie (). There is also a function context.abort () that aborts the current request.

Restart the program, go to http://localhost:8080/user/profile/? directly If ID =5, we’ll see our 401 page. When we log in and then access, we can access normally.

Here and now our Auth middleware is working.

🔄 refreshes the cookie

In the cookie setting above, there is a parameter to set the expiration time, so how long is the expiration time set? If the expiration time is too long, security risks may exist. If the expiration time is too short, users may find it inconvenient.

So we need to automatically refresh our cookie time when the cookie request is successful.

Modify our middleware code.

The first step is to retrieve the original cookie and then set a new cookie.

func Auth(a) gin.HandlerFunc {
	return func(context *gin.Context) {
		cookie, e := context.Request.Cookie("user_cookie")
		if e == nil {
			context.SetCookie(cookie.Name, cookie.Value, 1000, cookie.Path, cookie.Domain, cookie.Secure, cookie.HttpOnly)
			context.Next()
		} else {
			context.Abort()
			context.HTML(http.StatusUnauthorized, "401.tmpl".nil)}}}Copy the code

Restart our project, still open the console of our project, every time access to the interface that requires permissions, we will see the cookie expiration time is refreshed.

✍ summary

This chapter mainly describes how to add cookies, how to obtain cookies, and how to verify cookies and refresh cookies through middleware

👩💻 Code of this section

Github

Recommended reading

Gin(I):Hello Gin(II): Routing Router Gin(III): Template TMPL Gin(IV): Form submission checksum model binding Gin(V): Connection to MySQL Gin(VI): File upload Gin(VII): Use and definition of middleware

Personal public account

The latest articles will be shared on the public account, welcome to pay attention to