美文网首页
hasura 开发简书 day2

hasura 开发简书 day2

作者: 天高s | 来源:发表于2021-12-11 21:47 被阅读0次

官方认证指导文档
人话说就是登陆注册用户认证的解决方案

Webhook

SSO

JWT

JWT

授权访问

Hasura 支持基于角色的授权,其中通过为每个角色、表和操作(插入更新等)创建规则来完成访问控制。这些访问控制规则使用动态会话变量,这些变量从您的身份验证服务 随每个请求传递到 GraphQL 引擎。角色信息是从X-Hasura-RoleX-Hasura-Allowed-Roles 会话变量推断出来的。身份验证服务可以根据要求传递其他会话变量。

JWT 实现步骤

第 1 步:配置重启 graphql-engine

graphql-engine
为啥这么配看这个文档 https://hasura.io/docs/latest/graphql/core/auth/authentication/jwt.html

第 2 步 启动自己的 Auth 服务签发 token

官网有个 Flask 的例子,GraphQL API with Python & Flask: JWT authentication

可是我不太熟悉 python,后面想打包成 Docker 镜像估计得折腾一段时间,想了想还是用熟悉的 Golang 写一个,后续打镜像也不大,python 据说 pull 个原始镜像就有好几百M
花了两三个小时写了一个粗糙的版本,代码在文章最后,先直接上结果的例子


注册 登陆

先看下 token 里数据是啥,这个工具不错 https://www.box3.cn/tools/jwt.html

JWT payload

这个 token 客户端拿到后要放到 Http Header 的 Authorization: Bearer

这里的用户是 member, 去 Hasura console 配置一下权限


配置 article 权限
查询数据

如果想嵌套查询


image.png 返回没有 author 权限

用上面同样的方式配置一下 author 表的权限


author表 权限

再次请求

请求数据

GO 源码

package main

import (
    "crypto/hmac"
    "crypto/md5"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "io/ioutil"
    "log"
    "net/http"
    "strconv"
    "strings"
    "time"
)

const (
    hmacKey           = "kukuku"
    hasuraURL         = "http://localhost:8080/v1/graphql"
    jwtKey            = "LTExIDA8LTExIDA8LTExIDA8LTExIDA8"
    hasuraAdminSecret = "myadminsecretkey"
)

var client = &http.Client{}

func main() {

    http.HandleFunc("/signup", signupHandler)
    http.HandleFunc("/login", loginHandler)

    http.ListenAndServe("0.0.0.0:8086", nil)
}

func signupHandler(w http.ResponseWriter, r *http.Request) {
    email := r.FormValue("email")
    password := r.FormValue("password")
    encodePassword := hmacPassword(password)
    log.Println("email:", email, "password:", password, "hmac: ", encodePassword)
    query := `mutation CreateUser($email: String!, $password: String!) {\n  insert_user_one(object: {password: $password, email: $email}) {\n    id\n  }\n}\n`
    body := `{"operationName": "CreateUser", "query": "` + query + `", "variables":` + `{"email": "` + email + `", "password": "` + encodePassword + `"}}`
    log.Println(" signupBody:", body)
    resp, err := graphqlPost(body)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    defer resp.Body.Close()
    b, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("read request.Body failed, err:%v", err)
        w.WriteHeader(resp.StatusCode)
    } else {
        w.Write(b)
    }
}

func graphqlPost(body string) (*http.Response, error) {
    req, err := http.NewRequest("POST", hasuraURL, strings.NewReader(body))
    if err != nil {
        log.Println("create request err:", err)
        return nil, fmt.Errorf("build req:", err)
    }
    req.Header.Set("content-type", "application/json")
    req.Header.Set("x-hasura-admin-secret", hasuraAdminSecret)
    return client.Do(req)
}

func hmacPassword(password string) string {
    mac := hmac.New(md5.New, []byte(hmacKey))
    mac.Write([]byte(password))
    encodePassword := hex.EncodeToString(mac.Sum([]byte("")))
    return encodePassword
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
    email := r.FormValue("email")
    password := r.FormValue("password")
    encodePassword := hmacPassword(password)
    log.Println("email:", email, "password:", password, "hmac: ", encodePassword)
    query := `query FindByEmail($email: String!) {\n  user(where: {email: {_eq: $email}}) {\n    password\n    role\n    \n    id\n  }\n}\n`
    body := `{"operationName": "FindByEmail", "query": "` + query + `", "variables":` + `{"email": "` + email + `"}}`
    resp, err := graphqlPost(body)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    defer resp.Body.Close()
    bytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("read request.Body failed, err:%v", err)
        w.WriteHeader(resp.StatusCode)
    } else {
        var user UserResponse
        json.Unmarshal(bytes, &user)
        if len(user.Data.User) < 1 {
            w.Write([]byte("user not exists"))
            return
        }
        if user.Data.User[0].Password != encodePassword {
            w.Write([]byte("wrong password"))
            return
        }
        if token, err := genToken(user.Data.User[0]); err != nil {
            w.Write([]byte("build token error: " + err.Error()))
            return
        } else {
            w.Write([]byte(token))
        }
    }
}

type Claims struct {
    Name   string
    UserId string      `json:"x-hasura-user-id"`
    Role   string   `json:"x-hasura-default-role"`
    Roles  []string `json:"x-hasura-allowed-roles"`
    jwt.StandardClaims
}

func genToken(user User) (string, error) {
    expireTime := time.Now().Add(7 * 24 * time.Hour)
    claims := &Claims{
        Name:   user.Name,
        UserId: strconv.Itoa(user.Id),
        Role:   user.Role,
        Roles:  []string{user.Role},
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: expireTime.Unix(), //过期时间
            IssuedAt:  time.Now().Unix(),
            Issuer:    "127.0.0.1",  // 签名颁发者
            Subject:   "user token", //签名主题
        },
    }
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    return token.SignedString([]byte(jwtKey))
}

type UserResponse struct {
    Data struct {
        User []User `json:"user"`
    } `json:"data"`
}

type User struct {
    Password string `json:"password"`
    Role     string `json:"role"`
    Name     string `json:""`
    Id       int    `json:"id"`
}

相关文章

  • hasura 开发简书 day2

    官方认证指导文档[https://hasura.io/docs/latest/graphql/core/auth/...

  • hasura 开发简书 day1

    hasura 官网 https://hasura.io/[https://hasura.io/] 环境准备 doc...

  • hasura ARM版本编译及Docker镜像制作(一)

    hasura 是什么? 引用hasura官方的介绍 Hasura GraphQL引擎是一个高性能的GraphQL服...

  • 初入职场,小A的故事(上)day04

    欢迎先看看day2那篇What!生涯观从娃娃抓起? (day2) - 简书,我们简单聊了一下“内在世界”。 生涯运...

  • 简书产品常见问题

    简书公司和简书产品 · 攻略大全 内容提要 简书产品历史简书产生过程简书一开始是几个人开发的?简书什么时候开始开发...

  • 简书+day2

    大家好,我是灵兰,有梦想,有实践才可能成功。 今天是学习公众号的第二天,内容是定位公众号类型。我的公众号灵兰书香阁...

  • iOS - Swift 浅析

    Swift开发入门-基础知识,附demo - 简书 Swift开发入门-进阶知识(一),附demo - 简书 Sw...

  • 不怕麻烦,勇敢尝试

    30天专注成长计划Day2 因为参与成长计划需要打卡才使用的简书,而我也是第一次才听说简书,虽然麻烦,可知道了...

  • 简书日记day2

    最近单位的岗位调整 最近一直在做交接的工作 其中包括我手上的项目交接给别人 而别人手里的工作交接到我手里 在简书计...

  • 简书项目开发

    新建项目 1.已安装react的情况下,在桌面 shift + 右键 打开服务器;2.输入命令 create-...

网友评论

      本文标题:hasura 开发简书 day2

      本文链接:https://www.haomeiwen.com/subject/qrwqfrtx.html