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()
}

猜你喜欢

转载自www.cnblogs.com/Bccd/p/13406461.html