1. 程式人生 > 實用技巧 >beego 實現介面認證

beego 實現介面認證

我這裡實現的是一個簡單的認證方式:使用的固定token

本次主要想記錄的技術點是

  • 獲取使用者的請求引數和請求頭並在路由轉發前先做許可權校驗
  • 通過結構體構建巢狀json

服務端

首先在路由的初始化函式中

  • 定義許可權認證函式
  • 對介面url路由轉發前進行許可權認證
  • 從請求頭中獲取使用者名稱並註冊到ctx中,後端可以通過ctx獲取已註冊的變數

router.go

package routers

import (
    "go-common-lib/olog"
    "kafka/routers/api"
    "kafka/routers/ui"

    "github.com/astaxie/beego
" "github.com/astaxie/beego/context" ) // 認證通過api呼叫的請求使用者是否有token var ApiAuthFilter = func(ctx *context.Context) { if ctx.Request.RequestURI != "/auth-center/ui/auth/login" && ctx.Request.RequestURI != "/ui/platform/auth/login" { olog.Debug("start auth request") token := ctx.Request.Header.Get("
Authorization") if token == "xxx" { username := ctx.Request.Header.Get("userName") // userId := ctx.Request.Header.Get("userId") olog.Debug("request is ok ,username is ", username) // if username != "" && userId != "" { if username != ""
{ ctx.Input.SetData("username", username) // ctx.Input.SetData("userID", userId) } else { olog.Debug("username or userId is not validate") ctx.Redirect(401, "/401") } } else { olog.Debug("request token is not exists") ctx.Redirect(401, "/401") } } } func init() { //對使用者提供的介面 beego.InsertFilter("/kafka/api/v/*", beego.BeforeRouter, ApiAuthFilter) api2Ns := beego.NewNamespace("/kafka/api/v", api.DemandNs(), ) beego.AddNamespace(api2Ns) }

客戶端請求

package main

import (
    "bytes"    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

var urlBase = "http://localhost:8888"
func WhiteListApply() {
    //叢集變更表單資訊
    type ProduceWhitelistItem struct {
        User  string `json:"user"`
        Topic string `json:"topic"`
        Bns   string `json:"bns"`
    }
    type ConsumeWhitelistItem struct {
        User  string `json:"user"`
        Topic string `json:"topic"`
        Group string `json:"group"`
        Bns   string `json:"bns"`
    }

    type WhitelistFormInfo struct {
        DepartmentId         int                    `json:"departmentID"`
        DepartmentName       string                 `json:"departmentName"`
        ClusterName          string                 `valid:"Required" json:"clusterName" description:"叢集名稱"`
        CausesAndNeeds       string                 `valid:"Required" json:"causesAndNeeds" description:"申請原因及需求說明"`
        Approver             string                 `json:"approver"`
        ProWhitelistType     string                 `json:"proWhitelistType" description:"生產者白名單型別,bbb或ip"`
        ConsumeWhitelistType string                 `json:"consumeWhitelistType" description:"消費者白名單型別,bbb或ip"`
        ProduceWhitelist     []ProduceWhitelistItem `json:"produceData" description:"生產者白名單新增"`
        ConsumeWhitelist     []ConsumeWhitelistItem `json:"consumeData" description:"消費者白名單新增"`
    }

    var url = fmt.Sprintf("%s/kafka/api/v/demand/whiteListApply", urlBase)
    pro := make([]ProduceWhitelistItem, 2)
    pro[0] = ProduceWhitelistItem{"user1", "topic1", "*"}
    pro[1] = ProduceWhitelistItem{"user2", "topic2", "*"}
    args := &WhitelistFormInfo{
        DepartmentId:         000,
        DepartmentName:       "xxxx",
        ClusterName:          "demo_1",
        CausesAndNeeds:       "test",
        ProWhitelistType:     "IP",
        ConsumeWhitelistType: "bbb",
        ProduceWhitelist:     pro,
        ConsumeWhitelist:     []ConsumeWhitelistItem{},
    }
    reqBody, err := json.Marshal(args)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
    if err != nil {
        panic(err)
    }
    req.Header.Set("userName", "xxx")
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "xxx")
    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    fmt.Println("Response status:", resp.Status)
    fmt.Println("body:", string(body))
}

func main() {
WhiteListApply()
}