mirror of
https://github.com/gin-gonic/gin.git
synced 2025-08-05 23:38:35 +08:00
feat(auth): add proxy-server authentication (#3877)
This commit is contained in:
21
auth.go
21
auth.go
@ -15,6 +15,7 @@ import (
|
||||
|
||||
// AuthUserKey is the cookie name for user credential in basic auth.
|
||||
const AuthUserKey = "user"
|
||||
const AuthProxyUserKey = "proxy_user"
|
||||
|
||||
// Accounts defines a key/value for user/pass list of authorized logins.
|
||||
type Accounts map[string]string
|
||||
@ -89,3 +90,23 @@ func authorizationHeader(user, password string) string {
|
||||
base := user + ":" + password
|
||||
return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base))
|
||||
}
|
||||
|
||||
func BasicAuthForProxy(accounts Accounts, realm string) HandlerFunc {
|
||||
if realm == "" {
|
||||
realm = "Proxy Authorization Required"
|
||||
}
|
||||
realm = "Basic realm=" + strconv.Quote(realm)
|
||||
pairs := processAccounts(accounts)
|
||||
return func(c *Context) {
|
||||
proxyUser, found := pairs.searchCredential(c.requestHeader("Proxy-Authorization"))
|
||||
if !found {
|
||||
// Credentials doesn't match, we return 407 and abort handlers chain.
|
||||
c.Header("Proxy-Authenticate", realm)
|
||||
c.AbortWithStatus(http.StatusProxyAuthRequired)
|
||||
return
|
||||
}
|
||||
// The proxy_user credentials was found, set proxy_user's id to key AuthProxyUserKey in this context, the proxy_user's id can be read later using
|
||||
// c.MustGet(gin.AuthProxyUserKey).
|
||||
c.Set(AuthProxyUserKey, proxyUser)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user