网站项目开发建设合同,卡密网站建设,三维动画设计,域名大全gin框架39--重构 BasicAuth 中间件 介绍gin BasicAuth 解析自定义newAuth实现基础认证注意事项说明 介绍
每当我们打开一个网址的时候#xff0c;会自动弹出一个认证界面#xff0c;要求我们输入用户名和密码#xff0c;这种BasicAuth是最基础、最常见的认证方式#xff0… gin框架39--重构 BasicAuth 中间件 介绍gin BasicAuth 解析自定义newAuth实现基础认证注意事项说明 介绍
每当我们打开一个网址的时候会自动弹出一个认证界面要求我们输入用户名和密码这种BasicAuth是最基础、最常见的认证方式gin框架中提供了一种内置的方式但它只能用内置的用户和密码无法使用外部db中的用户和密码这种方式很多时候是不友好的。 为此本文根据gin.BasicAuth的原理对其就行重构实现一个简单的newAuth中间件该中间件可以代替默认的BasicAuth并且可以按需更改为自定义查询函数实现从外部db或者用户管理系统查询信息实现登录认证的功能。
gin BasicAuth 解析
博文 gin框架14–使用 BasicAuth 中间件 介绍了BasicAuth 中间件的基础使用方法直接使用 gin.BasicAuth(gin.Accounts{“foo”: “bar”, “austin”: “1234”, “lena”: “hello2”, “manu”: “4321”, }) 即可非常简单实用。
实际上当我们访问url的时候它会从请求的 Authorization 中获取用户信息并和gin.Accounts中内置用户对比如果用户存在就将用户名称存放在Context的 Keys map结构中方便后续查找或者获取用户信息如果不存在就设置c.Header(“WWW-Authenticate”, realm), 并返回c.AbortWithStatus(http.StatusUnauthorized)浏览器上的表现就是重新弹出输入用户名和密码的窗口 。
核心逻辑在 BasicAuthForRealm 方法中如下所示:
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {if realm {realm Authorization Required}realm Basic realm strconv.Quote(realm)pairs : processAccounts(accounts)return func(c *Context) {// Search user in the slice of allowed credentialsuser, found : pairs.searchCredential(c.requestHeader(Authorization))if !found {// Credentials doesnt match, we return 401 and abort handlers chain.c.Header(WWW-Authenticate, realm)c.AbortWithStatus(http.StatusUnauthorized)return}// The user credentials was found, set users id to key AuthUserKey in this context, the users id can be read later using// c.MustGet(gin.AuthUserKey).c.Set(AuthUserKey, user)}
}自定义newAuth实现基础认证
gin.BasicAuth 只能提供默认的认证功能且需要内置指定的用户|密码但实际在代码中hardcode大量用户信息是不科学的因此我们需要自己重构一个BasicAuth来实验基础认证功能。 此处实现了一个newAuth中间件该中间件会判断用户是否输入账号|密码并通过judgeUserExist来判断账号|密码是否正确正确则返回用户信息不正确则返回http.StatusUnauthorized 具体案例如下。
此处为了简洁方便此处直接内置了3个用户到users中并用 judgeUserExist 查询用户账号密码是否正确。实际项目中可将该方法更改为查询db无需在项目中hardcode内置用户。
package mainimport (encoding/base64fmtgithub.com/gin-gonic/ginnet/httpstrconvstrings
)var users gin.H{foo: gin.H{email: foobar.com, phone: 123433, pwd: bar},austin: gin.H{email: austinexample.com, phone: 666, pwd: 123},lena: gin.H{email: lenaguapa.com, phone: 523443, pwd: 456},
}func help() string {helpStr : hello gin:
127.0.0.1:8088/your-api
/auth/user
return helpStr
}func judgeUserExist(userName, userPwd string) (string, bool) {// 实际项目中将该函数更改为从db查询即可此处为了简单直接从预定的users中查询。msg : tag : falseif userInfo, ok : users[userName]; ok {pwd, ok : userInfo.(gin.H)[pwd]if ok pwd userPwd {msg fmt.Sprintf(用户%v密码正确, userName)tag true} else {msg fmt.Sprintf(用户%v密码不正确, userName)}} else {msg fmt.Sprintf(用户%v不存在, userName)}return msg, tag
}func getUserPwdFromAuthorization(auth string) (user, pwd string) {// auth[:6]Basic base64UserPwd, err : base64.StdEncoding.DecodeString(auth[6:])if err ! nil {panic(err)}base64UserPwdStr : string(base64UserPwd)colonIndex : strings.Index(base64UserPwdStr, :)user base64UserPwdStr[:colonIndex]pwd base64UserPwdStr[colonIndex1:]return user, pwd
}func newAuth(realm string) func(c *gin.Context) {if realm {realm Authorization Required}realm Basic realm strconv.Quote(realm)return func(c *gin.Context) {authHeader : c.Request.Header.Get(Authorization) // 获取请求头中的数据if authHeader {c.Header(WWW-Authenticate, realm)c.AbortWithStatus(http.StatusUnauthorized)return} else {user, pwd : getUserPwdFromAuthorization(authHeader)// fmt.Printf(user%v,pwd%v\n, user, pwd)msg, tag : judgeUserExist(user, pwd)if !tag {// c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{msg: msg, tag: tag})fmt.Println(msg)c.AbortWithStatus(http.StatusUnauthorized)return}c.Set(gin.AuthUserKey, user)}}
}func userHandler(c *gin.Context) {user : c.MustGet(gin.AuthUserKey).(string)c.IndentedJSON(http.StatusOK, gin.H{status: 200,msg: its fine,userInfo: users[user],})
}func main() {app : gin.Default()app.GET(/, func(c *gin.Context) {c.String(http.StatusOK, help())})authorized : app.Group(/auth, newAuth())authorized.GET(/user, userHandler)app.Run(:8088)
}输出:
注意事项
c.Header中需要添加 WWW-Authenticate 字段否则初次访问的时候不会弹出输入用户名、密码的框!!!
说明
测试环境 ubuntu22.04 Desktop go1.20.7参考文档 using-basicauth-middleware Gin框架 -- 中间件 文章转载自: http://www.morning.xywfz.cn.gov.cn.xywfz.cn http://www.morning.tsnq.cn.gov.cn.tsnq.cn http://www.morning.mlhfr.cn.gov.cn.mlhfr.cn http://www.morning.zljqb.cn.gov.cn.zljqb.cn http://www.morning.tcylt.cn.gov.cn.tcylt.cn http://www.morning.dtpqw.cn.gov.cn.dtpqw.cn http://www.morning.dmtbs.cn.gov.cn.dmtbs.cn http://www.morning.zpqk.cn.gov.cn.zpqk.cn http://www.morning.xqwq.cn.gov.cn.xqwq.cn http://www.morning.c7622.cn.gov.cn.c7622.cn http://www.morning.mspqw.cn.gov.cn.mspqw.cn http://www.morning.ndxss.cn.gov.cn.ndxss.cn http://www.morning.ahscrl.com.gov.cn.ahscrl.com http://www.morning.qklff.cn.gov.cn.qklff.cn http://www.morning.fpjw.cn.gov.cn.fpjw.cn http://www.morning.ttdxn.cn.gov.cn.ttdxn.cn http://www.morning.rjfr.cn.gov.cn.rjfr.cn http://www.morning.jtmql.cn.gov.cn.jtmql.cn http://www.morning.fhxrb.cn.gov.cn.fhxrb.cn http://www.morning.gnyhc.cn.gov.cn.gnyhc.cn http://www.morning.nqmdc.cn.gov.cn.nqmdc.cn http://www.morning.yrfxb.cn.gov.cn.yrfxb.cn http://www.morning.hnk25076he.cn.gov.cn.hnk25076he.cn http://www.morning.xgkxy.cn.gov.cn.xgkxy.cn http://www.morning.bpncd.cn.gov.cn.bpncd.cn http://www.morning.gcysq.cn.gov.cn.gcysq.cn http://www.morning.tbnpn.cn.gov.cn.tbnpn.cn http://www.morning.pcrzf.cn.gov.cn.pcrzf.cn http://www.morning.tsxg.cn.gov.cn.tsxg.cn http://www.morning.rqpgk.cn.gov.cn.rqpgk.cn http://www.morning.hwpcm.cn.gov.cn.hwpcm.cn http://www.morning.tsdjj.cn.gov.cn.tsdjj.cn http://www.morning.lhrwy.cn.gov.cn.lhrwy.cn http://www.morning.wpkr.cn.gov.cn.wpkr.cn http://www.morning.rfjmy.cn.gov.cn.rfjmy.cn http://www.morning.gskzy.cn.gov.cn.gskzy.cn http://www.morning.fdzzh.cn.gov.cn.fdzzh.cn http://www.morning.dpdr.cn.gov.cn.dpdr.cn http://www.morning.jwcmq.cn.gov.cn.jwcmq.cn http://www.morning.wxqmc.cn.gov.cn.wxqmc.cn http://www.morning.kwcnf.cn.gov.cn.kwcnf.cn http://www.morning.bkryb.cn.gov.cn.bkryb.cn http://www.morning.fqyxb.cn.gov.cn.fqyxb.cn http://www.morning.spfh.cn.gov.cn.spfh.cn http://www.morning.jpgfx.cn.gov.cn.jpgfx.cn http://www.morning.bypfj.cn.gov.cn.bypfj.cn http://www.morning.krlsz.cn.gov.cn.krlsz.cn http://www.morning.lxctl.cn.gov.cn.lxctl.cn http://www.morning.mcjxq.cn.gov.cn.mcjxq.cn http://www.morning.ymfzd.cn.gov.cn.ymfzd.cn http://www.morning.sfsjh.cn.gov.cn.sfsjh.cn http://www.morning.mfcbk.cn.gov.cn.mfcbk.cn http://www.morning.brmbm.cn.gov.cn.brmbm.cn http://www.morning.gxfzrb.com.gov.cn.gxfzrb.com http://www.morning.nqbpz.cn.gov.cn.nqbpz.cn http://www.morning.dwmmf.cn.gov.cn.dwmmf.cn http://www.morning.tztgq.cn.gov.cn.tztgq.cn http://www.morning.bnxnq.cn.gov.cn.bnxnq.cn http://www.morning.bqdpy.cn.gov.cn.bqdpy.cn http://www.morning.080203.cn.gov.cn.080203.cn http://www.morning.qtwd.cn.gov.cn.qtwd.cn http://www.morning.ghyfm.cn.gov.cn.ghyfm.cn http://www.morning.tfwr.cn.gov.cn.tfwr.cn http://www.morning.wgzgr.cn.gov.cn.wgzgr.cn http://www.morning.smj79.cn.gov.cn.smj79.cn http://www.morning.lffrh.cn.gov.cn.lffrh.cn http://www.morning.zzjpy.cn.gov.cn.zzjpy.cn http://www.morning.nytgk.cn.gov.cn.nytgk.cn http://www.morning.rfyff.cn.gov.cn.rfyff.cn http://www.morning.cfrz.cn.gov.cn.cfrz.cn http://www.morning.mrckk.cn.gov.cn.mrckk.cn http://www.morning.kkdbz.cn.gov.cn.kkdbz.cn http://www.morning.rwnx.cn.gov.cn.rwnx.cn http://www.morning.xfhms.cn.gov.cn.xfhms.cn http://www.morning.mrgby.cn.gov.cn.mrgby.cn http://www.morning.gpcy.cn.gov.cn.gpcy.cn http://www.morning.sqmbb.cn.gov.cn.sqmbb.cn http://www.morning.dglszn.com.gov.cn.dglszn.com http://www.morning.kmprl.cn.gov.cn.kmprl.cn http://www.morning.wmyqw.com.gov.cn.wmyqw.com