基于Gin框架隐藏Web系统登录页面
# 背景
我不太想泄露系统的Web登录页面,所以针对静态资源和根路径的请求我准备加一个401认证。
# 实现
后端框架是Gin,采用白名单方式,api接口走jwt认证,静态资源和根路径走basic认证。
func BasicAuth(c *gin.Context) (err error) {
if !strings.Contains(c.Request.URL.Path, "v1/") {
// 获取 BasicAuth 认证信息
username, password, ok := c.Request.BasicAuth()
if !ok {
c.Header("WWW-Authenticate", "Basic realm=Restricted")
c.JSON(
http.StatusUnauthorized,
gin.H{
"code": http.StatusUnauthorized,
})
return errors.New("用户未登录")
}
if config.Cfg.Web.BasicAuth.Username == username && config.Cfg.Web.BasicAuth.Password == password {
c.Next()
return
} else {
c.Header("WWW-Authenticate", "Basic realm=Restricted")
c.JSON(
http.StatusUnauthorized,
gin.H{
"code": http.StatusUnauthorized,
})
return errors.New("用户未登录")
}
}
return nil
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
通过验证后再显示前端即可。