热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

关于go-zero:gozero-dockercompose-搭建课件服务六完善jwt鉴权和返回结构

0、索引go-zerodocker-compose搭建课件服务(一):编写服务api和protogo-zerodocker-compose搭建课件服务(二):编写coursewarerpc服务go-zerodocker

0、索引

go-zero docker-compose 搭建课件服务(一):编写服务api和proto

go-zero docker-compose 搭建课件服务(二):编写courseware rpc服务

go-zero docker-compose 搭建课件服务(三):编写courseware api服务

go-zero docker-compose 搭建课件服务(四):生成Dockerfile并在docker-compose中启动

go-zero docker-compose 搭建课件服务(五):欠缺user服务

go-zero docker-compose 搭建课件服务(六):欠缺jwt鉴权和返回构造

go-zero docker-compose 搭建课件服务(七):prometheus+grafana服务监控

0.1源码地址

https://github.com/liuyuede123/go-zero-courseware

1、用户服务登录接口生成jwt token

user/api/etc/user.yaml中减少用于生成jwt的secret和过期工夫

...

Auth:
  AccessSecret: 38f9c7af24ff11edb92900163e30ef81
  AccessExpire: 86400

user/api/internal/config/config.go减少配置参数

...

Auth struct {
        AccessSecret string
        AccessExpire int64
}

在之前编写的登录逻辑中减少获取token的办法,并批改登录逻辑

...

func (l *UserLoginLogic) UserLogin(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
    login, err := l.svcCtx.UserRpc.Login(l.ctx, &userclient.LoginRequest{
        LoginName: req.LoginName,
        Password:  req.Password,
    })
    if err != nil {
        return nil, err
    }

    now := time.Now().Unix()
    login.Token, err = l.getJwtToken(l.svcCtx.Config.Auth.AccessSecret, now, l.svcCtx.Config.Auth.AccessExpire, int64(login.Id))
    if err != nil {
        return nil, status.Error(5000, err.Error())
    }
    return &types.LoginResponse{
        Id:    login.Id,
        Token: login.Token,
    }, nil
}

func (l *UserLoginLogic) getJwtToken(secretKey string, iat, seconds, userId int64) (string, error) {
    claims := make(jwt.MapClaims)
    claims["exp"] = iat + seconds
    claims["iat"] = iat
    claims["userId"] = userId
    token := jwt.New(jwt.SigningMethodHS256)
    token.Claims = claims
    return token.SignedString([]byte(secretKey))
}

2、用户明码加密

user/rpc/internal/logic/registerlogic.go批改代码加密明码

...

func (l *RegisterLogic) Register(in *user.RegisterRequest) (*user.RegisterResponse, error) {
    _, err := l.svcCtx.UserModel.FindOneByLoginName(l.ctx, in.LoginName)
    if err == nil {
        return nil, status.Error(5000, "登录名已存在")
    }

    if err != model.ErrNotFound {
        return nil, status.Error(500, err.Error())
    }

    pwd, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
    if err != nil {
        return nil, status.Error(500, err.Error())
    }
    newUser := model.User{
        LoginName: in.LoginName,
        Username:  in.Username,
        Sex:       in.Sex,
        Password:  string(pwd),
    }
    _, err = l.svcCtx.UserModel.Insert(l.ctx, &newUser)
    if err != nil {
        return nil, status.Error(500, err.Error())
    }

    return &user.RegisterResponse{}, nil
}

user/rpc/internal/logic/loginlogic.go 登录逻辑批改明码验证

...

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
    userInfo, err := l.svcCtx.UserModel.FindOneByLoginName(l.ctx, in.LoginName)
    if err == model.ErrNotFound {
        return nil, status.Error(5000, "用户不存在")
    }
    if err != nil {
        return nil, status.Error(500, err.Error())
    }

    err = bcrypt.CompareHashAndPassword([]byte(userInfo.Password), []byte(in.Password))
    if err != nil {
        return nil, status.Error(5000, "明码谬误")
    }

    return &user.LoginResponse{
        Id:    userInfo.Id,
        Token: "a.b.c",
    }, nil
}

3、其余接口减少鉴权中间件

批改courseware/api/courseware.api减少鉴权中间件

...

@server (
    jwt : Auth
)
service courseware {
    @handler coursewareAdd
    post /api/courseware/add (AddRequest) returns (AddResponse)

    @handler coursewareUpdate
    post /api/courseware/update (UpdateRequest) returns (UpdateResponse)

    @handler coursewareGet
    post /api/courseware/get (GetRequest) returns (GetResponse)

    @handler coursewareDelete
    post /api/courseware/delete (DeleteRequest) returns (DeleteResponse)

courseware/api/etc/courseware.yaml课件api减少auth配置

...

Auth:
  AccessSecret: 38f9c7af24ff11edb92900163e30ef81
  AccessExpire: 86400

courseware/api/internal/config/config.go减少auth配置

Auth struct {
        AccessSecret string
        AccessExpire int64
}

到courseware/api/目录下从新生成路由文件

goctl api go -api courseware.api -dir . -style gozero

用户服务获取用户信息接口须要减少权限校验

批改user/api/user.api减少鉴权中间件

...

service user {
    @handler userLogin
    post /api/user/login (LoginRequest) returns (LoginResponse)

    @handler userRegister
    post /api/user/register (RegisterRequest) returns (RegisterResponse)
}

@server (
    jwt : Auth
)
service user {

    @handler userInfo
    post /api/user/userInfo (UserInfoRequest) returns (UserInfoResponse)
}

第一步曾经生成auth相干配置不须要从新设置,到user/api/目录下更新路由

goctl api go -api user.api -dir . -style gozero

4、返回构造优化

课件api层新增courseware/api/response/response.go

package response

import (
    "github.com/zeromicro/go-zero/rest/httpx"
    "net/http"
)

type Body struct {
    Code    int         `json:"code"`
    Message string      `json:"message"`
    Data    interface{} `json:"data,omitempty"`
}

func Response(w http.ResponseWriter, resp interface{}, err error) {
    var body Body
    if err != nil {
        body.Code = 5000
        body.Message = err.Error()
        body.Data = nil
    } else {
        body.Code = 0
        body.Message = "OK"
        body.Data = resp
    }
    httpx.OkJson(w, body)
}

handler中批改返回构造

批改前

...

if err != nil {
            httpx.Error(w, err)
        } else {
            httpx.OkJson(w, resp)
        }

批改后

response.Response(w, resp, err)

用户api服务反复下面的步骤…


推荐阅读
author-avatar
长颈己
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有