彩虹女神跃长空,Go语言进阶之Go语言高性能Web框架Iris项目实战-JWT和中间件 ...

打印 上一主题 下一主题

主题 811|帖子 811|积分 2433

前文再续,上一回我们完成了用户的登录逻辑,将之前用户管理模块中添加的用户账号进行账号和密码的校验,过程中使用图形验证码强制进行人机交互,防止账号的密码被暴力破解。本回我们需要为登录成功的用户生成Token,并且通过Iris的中间件(Middleware)进行鉴权操作。
Iris模板复用

在生成Token之前,首先我们需要对项目的模板进行优化改造,目前存在的页面模板有三块,分别是:首页模板(index.html)、登录页模板(signin.html)、后台用户管理页模板(/admin/user.html),虽然页面并不多,但不难发现,有很多重复的代码,比方说,首页模板和登录页模板都有公共的头部导航菜单,没必要每个模板都写一遍相同的代码,再比如,三块模板都会有axios的封装逻辑,也没必要三块模板封装三次,除此之外,以后模板多了,不做复用,就会出现维护困难的问题。
首先提取页面模板的公共部分,比如头部导航,在views目录建立header.html:
  1. <nav >  
  2.       
  3.         
  4.   
  5.             
  6.             
  7.                
  8.             <img src="https://www.cnblogs.com/data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4K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nyLvooQfR5iujAnR9bxfY2xOVOxFS8SK3Le0l48VyYu1M8HRe5JD8wKPTjYnifaK3Wfn/GChYQ8ZAi6WRzWgqLV5YrsVLnZaVSoXU1g9gOIDwFySiGi+Zdrnzr7J3r+SMuszlcQCRn8lNGcTuSy2jOI7o9mxjZo+vR3ej3tN+ifRSOyUTS0+VMOid93cCubeiy/6TImS0QxRSCq2vxKr45zV+FQnjWH6D2xg+E9EatLcLAdHTgtGGD80D6jM0+aOl4wJgO/f96R2aJKCQ3yvgftRhdFMOpd6oAAAAASUVORK5CYII=" width="16" height="16" role="presentation" >  
  9.           <img src="https://www.cnblogs.com/data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KTMInWQAABlJJREFUWAm1V3tsFEUcntnXvXu0tBWo1ZZHihBjCEWqkHiNaMLDRKOtQSKaiCFKQtS/SbxiFCHGCIkmkBSMwZhQNTFoQZD0DFiwtCDFAkdDqBBBKFj63rvdnfH7zfVo5aFBj0l2Z/dm5vd98/0es8dYjlpr62az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dS2JcDVMN6xVOKZyrCGm8b108lrLRVzvptLH7IoEFLFANes6KnDi+uxfmvFnF17oALq5u1agu3/YfHkcSFzeSggV5eXRfIB7CHNcO5SUI+Ih5Ir7f4MAV9IqdFzdZgNpZw1Gcs1mNvgGbTbqQ9/cz7ZuuhgyYRQ49ljTyWHhr2DwpNHHFf+5gnWZ3Bharo+0TD5dNMw5vv9RlVpSRDHK4TlnoukhtYApuOHejSZQuo5g/A9BysdKRCyLl6062fN37OXMDlvUJtUrtmxo0avrW3wTrYs3jJ9RvRVChrmSmanPMpX2OXMsmDGh6AiEIwBAlvkOqIdBy+8JyAz8pz7QxiDth4KDy5uAlwzrWTnwC8Vc4KVAMZ3YUZ+IqoIjP3h5KFFX1ZMy3uW+7RhEDHgTi0zC9rS7uhPCDiNrGFyqBeERtKN/B0YlyFCkw0NJ5C0Ojv7zvT1a1WV1TuvZDdL4NTgB7CASYpsen6gqvG5jmTf5qHedADgkBl3D0nkSgNhZACDyi0FUKZRr3IdRjgN4WPPoFMIIegIK3mqd38fS80mcJKelM4szNyzZtQbkchGePuBRS8Eg9pHU8ojRQpSqs+ajAIwTjjUMQ/nvTNM0kicwYxZIYMh/891DYi+fvedB+c1xsm4lDU6ya+Axtz+RiAzEVYbajQOpq17F0R9QevNcEhfcU+xvyQQUalGJBSesqOkgPQ4YNyUZL9fSvUPDjoNAwN8/dwFjaczNkc3ptaMud1EIDtGcmXTcefO2cGSvKIFfp/2JIJxlq7xEl3nVPM4fDeIbPkD16/ptNc0bDu7qxbsu0R2JGywWMIjF2ft3tjfloAyQAGXiOn8hrqwbVvMXzaO+QeHXP6nF0wvX74Hf4NGG5GPjSlYoyM3P/0FbCT6zvM/yYoAAAAASUVORK5CYII=" width="16" height="16" role="presentation" >  
  10.   
  11.               
  12.   
  13.         <button type="button"  data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">  
  14.         菜单  
  15.          
  16.          
  17.          
  18.         </button>  
  19.         
  20.         
  21.         <ul >  
  22.           <li  ><a target="_blank" href="https://www.cnblogs.com/" title='刘悦'>Home</a></li>  
  23.           <li ><a target="_blank" href="https://www.cnblogs.com/l_id_1" title='python编程'>Python</a></li>  
  24.           <li ><a target="_blank" href="https://www.cnblogs.com/l_id_2" title='前端技术'>Web Design</a></li>  
  25.           <li ><a target="_blank" href="https://www.cnblogs.com/l_id_3" title='数据库相关技术(mysql,redis)'>Db & SQL</a></li>  
  26.           <li ><a target="_blank" href="https://www.cnblogs.com/l_id_4" title='Mac & Linux(苹果系统和linux相关技术)'>Mac & Linux</a></li>  
  27.           <li ><a target="_blank" href="https://www.cnblogs.com/l_id_5" title='Go 和 Ruby 相关实践'>Go & Ruby</a></li>  
  28.           <li ><a target="_blank" href="https://www.cnblogs.com/l_id_6" title='生活和工作'>Life & Work</a></li>  
  29.           <li ><a target="_blank" href="https://www.cnblogs.com/resume" title='刘悦简历'>Resume</a></li>  
  30.         </ul>  
  31.   
  32.   
  33.             
  34.             <img src="https://www.cnblogs.com/data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6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AnR9bxfY2xOVOxFS8SK3Le0l48VyYu1M8HRe5JD8wKPTjYnifaK3Wfn/GChYQ8ZAi6WRzWgqLV5YrsVLnZaVSoXU1g9gOIDwFySiGi+Zdrnzr7J3r+SMuszlcQCRn8lNGcTuSy2jOI7o9mxjZo+vR3ej3tN+ifRSOyUTS0+VMOid93cCubeiy/6TImS0QxRSCq2vxKr45zV+FQnjWH6D2xg+E9EatLcLAdHTgtGGD80D6jM0+aOl4wJgO/f96R2aJKCQ3yvgftRhdFMOpd6oAAAAASUVORK5CYII=" width="16" height="16" role="presentation" >  
  35.           <img src="https://www.cnblogs.com/data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KTMInWQAABlJJREFUWAm1V3tsFEUcntnXvXu0tBWo1ZZHihBjCEWqkHiNaMLDRKOtQSKaiCFKQtS/SbxiFCHGCIkmkBSMwZhQNTFoQZD0DFiwtCDFAkdDqBBBKFj63rvdnfH7zfVo5aFBj0l2Z/dm5vd98/0es8dYjlpr62azufnDQNZcU1Pci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VOKZyrCGm8b108lrLRVzvptLH7IoEFLFANes6KnDi+uxfmvFnF17oALq5u1agu3/YfHkcSFzeSggV5eXRfIB7CHNcO5SUI+Ih5Ir7f4MAV9IqdFzdZgNpZw1Gcs1mNvgGbTbqQ9/cz7ZuuhgyYRQ49ljTyWHhr2DwpNHHFf+5gnWZ3Bharo+0TD5dNMw5vv9RlVpSRDHK4TlnoukhtYApuOHejSZQuo5g/A9BysdKRCyLl6062fN37OXMDlvUJtUrtmxo0avrW3wTrYs3jJ9RvRVChrmSmanPMpX2OXMsmDGh6AiEIwBAlvkOqIdBy+8JyAz8pz7QxiDth4KDy5uAlwzrWTnwC8Vc4KVAMZ3YUZ+IqoIjP3h5KFFX1ZMy3uW+7RhEDHgTi0zC9rS7uhPCDiNrGFyqBeERtKN/B0YlyFCkw0NJ5C0Ojv7zvT1a1WV1TuvZDdL4NTgB7CASYpsen6gqvG5jmTf5qHedADgkBl3D0nkSgNhZACDyi0FUKZRr3IdRjgN4WPPoFMIIegIK3mqd38fS80mcJKelM4szNyzZtQbkchGePuBRS8Eg9pHU8ojRQpSqs+ajAIwTjjUMQ/nvTNM0kicwYxZIYMh/891DYi+fvedB+c1xsm4lDU6ya+Axtz+RiAzEVYbajQOpq17F0R9QevNcEhfcU+xvyQQUalGJBSesqOkgPQ4YNyUZL9fSvUPDjoNAwN8/dwFjaczNkc3ptaMud1EIDtGcmXTcefO2cGSvKIFfp/2JIJxlq7xEl3nVPM4fDeIbPkD16/ptNc0bDu7qxbsu0R2JGywWMIjF2ft3tjfloAyQAGXiOn8hrqwbVvMXzaO+QeHXP6nF0wvX74Hf4NGG5GPjSlYoyM3P/0FbCT6zvM/yYoAAAAASUVORK5CYII=" width="16" height="16" role="presentation" >  
  36.   
  37.          
  38.           <form action="/Index_search" method ="GET"  >  
  39.             <input type="search" name="text"  placeholder="Search" required="required" >  
  40.           </form>  
  41.          
  42.   
  43.   
  44.         
  45.       
  46.       
  47.   </nav>
复制代码
随后,在需要头部导航的模板进行引入操作,比如修改signin.html:
  1. ${ render "header.html" }
复制代码
注意,使用${}是为了避免和前端的Vue.js标签冲突。
同样地,将封装axios.js逻辑单独抽取出来myaxios.html:
  1. [/code]然后在需要的地方进行引入操作:
  2. [code]${ render "myaxios.html" }
复制代码
如此,我们只需要维护模板的公共部分即可。
修改后,项目的结构如下:
  1. .  
  2. ├── README.md  
  3. ├── assets  
  4. │ ├── css  
  5. │ │ └── style.css  
  6. │ └── js  
  7. │     ├── axios.js  
  8. │     └── vue.js  
  9. ├── database  
  10. │ └── database.go  
  11. ├── favicon.ico  
  12. ├── go.mod  
  13. ├── go.sum  
  14. ├── handler  
  15. │ ├── admin.go  
  16. │ └── user.go  
  17. ├── main.go  
  18. ├── model  
  19. │ └── model.go  
  20. ├── mytool  
  21. │ └── mytool.go  
  22. ├── tmp  
  23. │ └── runner-build  
  24. └── views  
  25.     ├── admin  
  26.     │ └── user.html  
  27.     ├── admin_header.html  
  28.     ├── header.html  
  29.     ├── index.html  
  30.     ├── myaxios.html  
  31.     ├── signin.html  
  32.     └── test.html
复制代码
JWT生成逻辑

JSON Web Token (JWT)是一个互联网应用的开放标准(RFC 7519),它定义了一种紧凑的、自包含的方式,用于作为JSON对象在各方之间安全地传输信息,这种信息可以被验证和信任,因为它是数字签名的。
说白了,登录成功以后,生成一个 JSON 对象,返回给前端,就像下面这样:
  1. {  
  2. "uid":1  
  3. }
复制代码
这之后,用户与服务端通信的时候,所有请求都要带着这个JSON 对象。服务器完全只靠这个对象认定用户身份。为了防止JSON对象被篡改,服务器在生成这个对象的时候,会加上签名,变成这种模样:
  1. eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVaWQiOjEsImlhdCI6MTY2MTg0MjYxMCwiZXhwIjoxNjYxODQ1NjEwfQ.BXK9awvVCk7L3JAnDGt9z6U9TOjPCpI0AcHRu1eq_mo
复制代码
这玩意就是普遍意义上的Token,俗称“令牌”。
在我们的项目中,需要为登录校验通过的账号生成Token,首先安装jwt包:
  1. go get -u github.com/kataras/iris/v12/middleware/jwt
复制代码
随后修改本地的工具包mytool.jwt:
  1. package mytool  
  2.   
  3. import (  
  4.         "crypto/md5"  
  5.         "fmt"  
  6.         "io"  
  7.         "time"  
  8.   
  9.         "github.com/dchest/captcha"  
  10.         "github.com/kataras/iris/v12"  
  11.         "github.com/kataras/iris/v12/middleware/jwt"  
  12. )  
  13.   
  14.   
  15. var SigKey = []byte("signature_hmac_secret_shared_key")  
  16.   
  17. type PlayLoad struct {  
  18.         Uid uint  
  19. }  
  20.   
  21. func GenerateToken(uid uint) string {  
  22.   
  23.         signer := jwt.NewSigner(jwt.HS256, SigKey, 50*time.Minute)  
  24.         claims := PlayLoad{Uid: uid}  
  25.   
  26.         token, err := signer.Sign(claims)  
  27.         if err != nil {  
  28.                 fmt.Println(err)  
  29.   
  30.         }  
  31.   
  32.         s := string(token)  
  33.   
  34.         return s  
  35.   
  36. }
复制代码
众所周知,Token由三部分组成:头部、载荷以及秘钥。这里SigKey字符为签名秘钥,PlayLoad结构体为载荷信息,这里通过签名生成一个字符格式的token,注意返回前端时,需要强转为字符串。
需要注意的是,生成签名时使用的是HS256算法,同时为了确保安全性,token设置生命周期,这里为50分钟。
随后修改用户登录逻辑,将生成好的token返回给前端:
  1. //登录动作  
  2. func Signin(ctx iris.Context) {  
  3.   
  4.         ret := make(map[string]interface{}, 0)  
  5.   
  6.         cid := ctx.PostValue("cid")  
  7.         code := ctx.PostValue("code")  
  8.   
  9.         if captcha.VerifyString(cid, code) == false {  
  10.   
  11.                 ret["errcode"] = 2  
  12.                 ret["msg"] = "登录失败,验证码错误"  
  13.                 ctx.JSON(ret)  
  14.                 return  
  15.   
  16.         }  
  17.   
  18.         db := database.Db()  
  19.         defer func() {  
  20.                 _ = db.Close()  
  21.         }()  
  22.   
  23.         Username := ctx.PostValue("username")  
  24.         Password := ctx.PostValue("password")  
  25.   
  26.         user := &model.User{}  
  27.   
  28.         db.Where(&model.User{Username: Username, Password: mytool.Make_password((Password))}).First(&user)  
  29.   
  30.         if user.ID == 0 {  
  31.   
  32.                 ret["errcode"] = 1  
  33.                 ret["msg"] = "登录失败,账号或者密码错误"  
  34.                 ctx.JSON(ret)  
  35.                 return  
  36.   
  37.         }  
  38.   
  39.         token := mytool.GenerateToken(user.ID)  
  40.   
  41.         fmt.Println(token)  
  42.   
  43.         ret["errcode"] = 0  
  44.         ret["msg"] = "登录成功"  
  45.         ret["username"] = user.Username  
  46.         ret["token"] = token  
  47.         ctx.JSON(ret)  
  48.   
  49. }
复制代码
前端接收的返回值为:
  1. {  
  2.     "errcode": 0,  
  3.     "msg": "登录成功",  
  4.     "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVaWQiOjEsImlhdCI6MTY2MTg0MzI5MSwiZXhwIjoxNjYxODQ2MjkxfQ.547z3nv4qj2-UeHTzfeG_qSsnFZD2DFyCP9gNZ-QiHA",  
  5.     "username": "123"  
  6. }
复制代码
随后前端收到token后,将其存储localstorage,然后跳转到后台页面:
  1. //登录请求  
  2.                 signin:function(){  
  3.   
  4.   
  5.                     this.myaxios("http://localhost:5000/signin/","post",{"username":this.username,"password":this.password,"cid":this.cid,"code":this.code}).then(data => {  
  6.                         console.log(data)  
  7.                         alert(data.msg);  
  8.   
  9.                         localStorage.setItem("token",data.token);  
  10.   
  11.                         window.location.href = "/admin/user/"  
  12.   
  13.                     });  
  14.   
  15.                 }
复制代码
localStorage存储是永久的,如果对安全性要求较高,可以采用sessionStorage,token生命周期就会跟随浏览器进程,但之前设置的token生命周期就没意义了,各有利弊,各自权衡。
中间件(Middleware)鉴权

所谓中间件,是一类提供系统软件和应用软件之间连接、便于软件各部件之间的沟通的软件,应用软件可以借助中间件在不同的技术架构之间共享信息与资源。
说白了,就是在所有需要鉴权的接口前面加一层逻辑,便于批量管理和控制:
  1. verifier := jwt.NewVerifier(jwt.HS256, mytool.SigKey)  
  2.           
  3.   
  4.         verifyMiddleware := verifier.Verify(func() interface{} {  
  5.   
  6.                 return new(mytool.PlayLoad)  
  7.         })
复制代码
这里声明中间件变量verifyMiddleware,该变量会返回一个载荷结构体对象。
随后,为所有的后台接口、包括后台模板添加中间件:
  1. adminhandler := app.Party("/admin")  
  2.           
  3.   
  4.         adminhandler.Use(verifyMiddleware)  
  5.   
  6.         adminhandler.Get("/userlist/", handler.Admin_userlist)  
  7.         adminhandler.Delete("/user_action/", handler.Admin_userdel)  
  8.         adminhandler.Put("/user_action/", handler.Admin_userupdate)  
  9.         adminhandler.Post("/user_action/", handler.Admin_useradd)  
  10.         adminhandler.Get("/user/", handler.Admin_user_page)
复制代码
如此,所有后台操作都需要中间件的鉴权操作。
换句话说,如果请求地址中没有token或者token不合法,就不会返回正常数据。
访问:http://localhost:5000/admin/user 如图所示:

如果带着token:

当然了,之后所有的后台请求都需要携带token,所以改造上面封装的myaxios.html:
[code][/code]藉此,每个后端请求都会携带token。
结语

JWT形式的认证体系将用户状态分散到了客户端中,相比于服务端的session存储,可以明显减轻服务端的内存压力,此外,使用Iris中间件鉴权的方式有助于提高代码的重用性,也更便于维护,更加优雅。该项目已开源在Github:https://github.com/zcxey2911/IrisBlog ,与君共觞,和君共勉。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

三尺非寒

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表