iris 使用基本身份驗(yàn)證

2022-03-26 14:07 更新

HTTP 基本身份驗(yàn)證是對 Web 資源實(shí)施訪問控制的最簡單技術(shù),因?yàn)樗恍枰?nbsp;cookie、會(huì)話標(biāo)識(shí)符或登錄頁面;相反,HTTP Basic 身份驗(yàn)證使用 HTTP 標(biāo)頭中的標(biāo)準(zhǔn)字段。

基本身份驗(yàn)證中間件包含在 Iris 框架中,因此您無需單獨(dú)安裝。

導(dǎo)入中間件:

import "github.com/kataras/iris/v12/middleware/basicauth"

使用其?Options?結(jié)構(gòu)配置中間件:

opts := basicauth.Options{
    Allow: basicauth.AllowUsers(map[string]string{
        "username": "password",
    }),
    Realm:        "Authorization Required",
    ErrorHandler: basicauth.DefaultErrorHandler,
    // [...more options]
}

初始化中間件:

auth := basicauth.New(opts)

上述步驟與Default功能相同:

auth := basicauth.Default(map[string]string{
    "username": "password",
})

使用自定義的用戶切片:

// The struct value MUST contain a Username and Passwords fields
// or GetUsername() string and GetPassword() string methods.
type User struct {
    Username string
    Password string
}

// [...]
auth := basicauth.Default([]User{...})

可選地從文件加載用戶,密碼使用bcrypt加密:

bcrypt包:golang.org/x/crypto/bcrypt

auth := basicauth.Load("users.yml", basicauth.BCRYPT)

同樣可以使用Options(推薦)實(shí)現(xiàn):

opts := basicauth.Options{
    Allow: basicauth.AllowUsersFile("users.yml", basicauth.BCRYPT),
    Realm: basicauth.DefaultRealm,
    // [...more options]
}

auth := basicauth.New(opts)

users.yml將如下所示:

- username: kataras
  password: $2a$10$Irg8k8HWkDlvL0YDBKLCYee6j6zzIFTplJcvZYKA.B8/clHPZn2Ey
  # encrypted of kataras_pass
  role: admin
- username: makis
  password: $2a$10$3GXzp3J5GhHThGisbpvpZuftbmzPivDMo94XPnkTnDe7254x7sJ3O
  # encrypted of makis_pass
  role: member

注冊中間件:

// Register to all matched routes
// under a Party and its children.
app.Use(auth)

// OR/and register to all http error routes.
app.UseError(auth)

// OR register under a path prefix of a specific Party,
// including all http errors of this path prefix.
app.UseRouter(auth)

// OR register to a specific Route before its main handler.
app.Post("/protected", auth, routeHandler)

檢索用戶名和密碼:

func routeHandler(ctx iris.Context) {
    username, password, _ := ctx.Request().BasicAuth()
    // [...]
}

檢索 User 值:

func routeHandler(ctx iris.Context) {
    user := ctx.User().(*iris.SimpleUser)
    // user.Username
    // user.Password
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)