go-zero docker-compose 搭建课件服务(六):完善jwt鉴权和返回结构

算法流星
• 阅读 907

0、转载

go-zero docker-compose 搭建课件服务(六):完善jwt鉴权和返回结构

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服务重复上面的步骤...

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Stella981 Stella981
3年前
C# Aspose.Cells导出xlsx格式Excel,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
报错信息:最近打开下载的Excel,会报如下错误。(xls格式不受影响)!(https://oscimg.oschina.net/oscnet/2b6f0c8d7f97368d095d9f0c96bcb36d410.png)!(https://oscimg.oschina.net/oscnet/fe1a8000d00cec3c
Stella981 Stella981
3年前
Linux查看GPU信息和使用情况
1、Linux查看显卡信息:lspci|grepivga2、使用nvidiaGPU可以:lspci|grepinvidia!(https://oscimg.oschina.net/oscnet/36e7c7382fa9fe49068e7e5f8825bc67a17.png)前边的序号"00:0f.0"是显卡的代
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Stella981 Stella981
3年前
Spring Cloud微服务架构从入门到会用(五)—服务网关鉴权
上一篇文章我们集成了服务网关SpringCloudGateway,所有的服务请求都可以通过Gateway访问。那我们就可在服务网关这一层对用户的请求进行鉴权,判断是否可以访问路由的API接口。接下来我们开始增加鉴权,这里我们使用jwt1\.创建授权服务module按照第二篇文章创建一个module,起名为appauth。
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
Github标星5300+,专门为程序员开发文档开源管理系统,我粉了
!(https://oscimg.oschina.net/oscnet/a11909a041dac65b1a36b2ae8b9bcc5c432.jpg)码农那点事儿关注我们,一起学习进步!(https://oscimg.oschina.net/oscnet/f4cce1b7389cb00baaab228e455da78d0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
5个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
算法流星
算法流星
Lv1
期待生活有惊喜,盼望事事有回应。
文章
3
粉丝
0
获赞
0