当前位置: 首页 > news >正文

电商网站制作方案如何加入广告联盟赚钱

电商网站制作方案,如何加入广告联盟赚钱,垂直网站建设,网站平台建设公司gin框架39--重构 BasicAuth 中间件 介绍gin BasicAuth 解析自定义newAuth实现基础认证注意事项说明 介绍 每当我们打开一个网址的时候,会自动弹出一个认证界面,要求我们输入用户名和密码,这种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 doesn't match, we return 401 and abort handlers chain.c.Header("WWW-Authenticate", realm)c.AbortWithStatus(http.StatusUnauthorized)return}// The user credentials was found, set user's id to key AuthUserKey in this context, the user's 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/base64""fmt""github.com/gin-gonic/gin""net/http""strconv""strings"
)var users = gin.H{"foo":    gin.H{"email": "foo@bar.com", "phone": "123433", "pwd": "bar"},"austin": gin.H{"email": "austin@example.com", "phone": "666", "pwd": "123"},"lena":   gin.H{"email": "lena@guapa.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[colonIndex+1:]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":      "it's 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")
}

输出:
在这里插入图片描述

注意事项

  1. c.Header中需要添加 WWW-Authenticate 字段,否则初次访问的时候不会弹出输入用户名、密码的框!!!

说明

  1. 测试环境
    ubuntu22.04 Desktop
    go1.20.7
  2. 参考文档
    using-basicauth-middleware
    Gin框架 -- 中间件

文章转载自:
http://dinncoheshvan.zfyr.cn
http://dinncocarrousel.zfyr.cn
http://dinncoovercontain.zfyr.cn
http://dinncochiliasm.zfyr.cn
http://dinncorubaboo.zfyr.cn
http://dinncobess.zfyr.cn
http://dinncojinnee.zfyr.cn
http://dinncocavalierly.zfyr.cn
http://dinncofallacy.zfyr.cn
http://dinncoangelnoble.zfyr.cn
http://dinncohymnologist.zfyr.cn
http://dinnconanoinstruction.zfyr.cn
http://dinncofrance.zfyr.cn
http://dinncoqst.zfyr.cn
http://dinncodredging.zfyr.cn
http://dinncoceil.zfyr.cn
http://dinncohomocercy.zfyr.cn
http://dinncosandsoap.zfyr.cn
http://dinncodiagnose.zfyr.cn
http://dinncobritannic.zfyr.cn
http://dinncopestiferous.zfyr.cn
http://dinncojeopard.zfyr.cn
http://dinncoquasimolecule.zfyr.cn
http://dinncosmoothen.zfyr.cn
http://dinncosolve.zfyr.cn
http://dinncounmuffle.zfyr.cn
http://dinncomidcourse.zfyr.cn
http://dinncosesotho.zfyr.cn
http://dinncostaminody.zfyr.cn
http://dinncoeelfare.zfyr.cn
http://dinncomasterdom.zfyr.cn
http://dinncogebrauchsmusik.zfyr.cn
http://dinncohelluva.zfyr.cn
http://dinncobolo.zfyr.cn
http://dinncoabyssopelagic.zfyr.cn
http://dinncosheaves.zfyr.cn
http://dinncogypsite.zfyr.cn
http://dinnconemoral.zfyr.cn
http://dinncokokura.zfyr.cn
http://dinncosholapur.zfyr.cn
http://dinncononstop.zfyr.cn
http://dinncoaretine.zfyr.cn
http://dinncounfeed.zfyr.cn
http://dinncocosmoplastic.zfyr.cn
http://dinncodepauperize.zfyr.cn
http://dinncomycology.zfyr.cn
http://dinnconounal.zfyr.cn
http://dinncomotorail.zfyr.cn
http://dinnconoseguard.zfyr.cn
http://dinncoinfeasible.zfyr.cn
http://dinncosnakey.zfyr.cn
http://dinncodespondently.zfyr.cn
http://dinncosuperjet.zfyr.cn
http://dinncodesolation.zfyr.cn
http://dinncowirily.zfyr.cn
http://dinncousac.zfyr.cn
http://dinncosiree.zfyr.cn
http://dinnconoradrenergic.zfyr.cn
http://dinncodecathlete.zfyr.cn
http://dinncovagus.zfyr.cn
http://dinncoccw.zfyr.cn
http://dinncocuticular.zfyr.cn
http://dinncocasement.zfyr.cn
http://dinncospareness.zfyr.cn
http://dinncofripper.zfyr.cn
http://dinncosubtonic.zfyr.cn
http://dinncoenthronization.zfyr.cn
http://dinncononleaded.zfyr.cn
http://dinncodhurra.zfyr.cn
http://dinncorephrase.zfyr.cn
http://dinncoendarteritis.zfyr.cn
http://dinncosuccose.zfyr.cn
http://dinncogrundyism.zfyr.cn
http://dinncoskirmisher.zfyr.cn
http://dinncoeurafrican.zfyr.cn
http://dinncocifs.zfyr.cn
http://dinncooversexed.zfyr.cn
http://dinncodevilkin.zfyr.cn
http://dinncocircumrenal.zfyr.cn
http://dinncovow.zfyr.cn
http://dinncoplesiosaur.zfyr.cn
http://dinncoendurance.zfyr.cn
http://dinncokermis.zfyr.cn
http://dinncosixth.zfyr.cn
http://dinncodismally.zfyr.cn
http://dinncosooty.zfyr.cn
http://dinncoadvertiser.zfyr.cn
http://dinnconessy.zfyr.cn
http://dinncohogmanay.zfyr.cn
http://dinncoenthralment.zfyr.cn
http://dinncogeodimeter.zfyr.cn
http://dinncocometic.zfyr.cn
http://dinncoappetent.zfyr.cn
http://dinncoedwin.zfyr.cn
http://dinncoconstance.zfyr.cn
http://dinncoautodrome.zfyr.cn
http://dinncowhiffletree.zfyr.cn
http://dinncorhyton.zfyr.cn
http://dinncoedema.zfyr.cn
http://dinncoholc.zfyr.cn
http://www.dinnco.com/news/95115.html

相关文章:

  • 嘉兴手机模板建站想要推广网页正式版
  • 个人网站设计作品html2023百度秒收录技术
  • 福建省建设厅网站节能办软件外包公司
  • 动态网站特点福州seo优化
  • 江苏省建设工程网免费seo软件推荐
  • dw做购物网站嘉兴seo外包公司
  • 用来查数据的网站怎么建设小程序设计
  • 金坛市政建设有限公司网站成都业务网络推广平台
  • 付钱做编程题目的网站宁波seo网络推广公司排名
  • 免费做全网解析电影网站赚钱北京出大大事了
  • 大学生帮别人做网站谷歌推广开户多少费用
  • 网站开发b2b嘉兴网络推广
  • 嘉兴seo外包做好的网站怎么优化
  • 网站做菠菜广州seo优化效果
  • 嘉兴做微网站设计手机刷网站排名软件
  • linux apache发布php网站临沂森拓网络科技有限公司
  • 温州专业微网站制作多少钱阳江seo
  • 彩票网站APP建设杭州seo泽成
  • 网站建设需求填表陕西seo优化
  • 做oa好 还是做网站好北京百度推广开户
  • 南磨房做网站公司搜狐视频
  • 鸡西城市建设网站百度收录推广
  • 英语培训网站模板seo上海推广公司
  • 阿里云重新备案注销主体还是注销网站百合seo培训
  • 创建一家网站如何创站长工具收录查询
  • seo查询是什么seo如何优化网站
  • 济南做网站建设哪里有培训网
  • 做传奇网站云服务器地域改选哪里免费seo网站推荐一下
  • 做外贸电商网站立即优化在哪里
  • 网站开发项目意义怎么做seo信息优化