golang进行简单权限认证的实现
本篇文章向大家介绍《golang进行简单权限认证的实现》,主要包括权限认证,具有一定的参考价值,需要的朋友可以参考一下。
使用JWT进行认证
JSON Web Tokens (JWT) are a more modern approach to authentication.
As the web moves to a greater separation between the client and server, JWT provides a wonderful alternative to traditional cookie based authentication models.
JWTs provide a way for clients to authenticate every request without having to maintain a session or repeatedly pass login credentials to the server.
用户注册之后, 服务器生成一个 JWT token返回给浏览器, 浏览器向服务器请求数据时将 JWT token 发给服务器, 服务器用 signature 中定义的方式解码
JWT 获取用户信息.
一个 JWT token包含3部分:
1 header: 告诉我们使用的算法和 token 类型
2 Payload: 必须使用 sub key 来指定用户 ID, 还可以包括其他信息比如 email, username 等.
3 Signature: 用来保证 JWT 的真实性. 可以使用不同算法
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/codegangsta/negroni"
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
)
const (
SecretKey = "welcome ---------"
)
func fatal(err error) {
if err != nil {
log.Fatal(err)
}
}
type UserCredentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Password string `json:"password"`
}
type Response struct {
Data string `json:"data"`
}
type Token struct {
Token string `json:"token"`
}
func StartServer() {
http.HandleFunc("/login", LoginHandler)
http.Handle("/resource", negroni.New(
negroni.HandlerFunc(ValidateTokenMiddleware),
negroni.Wrap(http.HandlerFunc(ProtectedHandler)),
))
log.Println("Now listening...")
http.ListenAndServe(":8087", nil)
}
func main() {
StartServer()
}
func ProtectedHandler(w http.ResponseWriter, r *http.Request) {
response := Response{"Gained access to protected resource"}
JsonResponse(response, w)
}
func LoginHandler(w http.ResponseWriter, r *http.Request) {
var user UserCredentials
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
w.WriteHeader(http.StatusForbidden)
fmt.Fprint(w, "Error in request")
return
}
if strings.ToLower(user.Username) != "someone" {
if user.Password != "p@ssword" {
w.WriteHeader(http.StatusForbidden)
fmt.Println("Error logging in")
fmt.Fprint(w, "Invalid credentials")
return
}
}
token := jwt.New(jwt.SigningMethodHS256)
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Add(time.Hour * time.Duration(1)).Unix()
claims["iat"] = time.Now().Unix()
token.Claims = claims
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "Error extracting the key")
fatal(err)
}
tokenString, err := token.SignedString([]byte(SecretKey))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "Error while signing the token")
fatal(err)
}
response := Token{tokenString}
JsonResponse(response, w)
}
func ValidateTokenMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
token, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor,
func(token *jwt.Token) (interface{}, error) {
return []byte(SecretKey), nil
})
if err == nil {
if token.Valid {
next(w, r)
} else {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "Token is not valid")
}
} else {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "Unauthorized access to this resource")
}
}
func JsonResponse(response interface{}, w http.ResponseWriter) {
json, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(json)
}


文中关于golang的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《golang进行简单权限认证的实现》文章吧,也可关注golang学习网公众号了解相关技术文章。
Go语言中CGO的使用实践
- 上一篇
- Go语言中CGO的使用实践
- 下一篇
- Go语言使用钉钉机器人推送消息的实现示例
-
- 无辜的背包
- 这篇博文真及时,太细致了,太给力了,收藏了,关注楼主了!希望楼主能多写Golang相关的文章。
- 2022-12-31 20:11:30
-
- Golang · Go教程 | 13小时前 | 标准库 · 基准测试 · Go教程 · 字符串拼接 · Go 字符串拼接 strings.Builder bytes.Buffer []byte
- Go 拼接字符串怎么选:strings.Builder、bytes.Buffer 和 []byte 的边界
- 188浏览 收藏
-
- Golang · Go教程 | 15小时前 | golang · Timer · 并发编程 · time.After · 性能排查 · time.After go timer Go 1.23 NewTimer Timer.Reset Timer.Stop
- Go 1.23 以后还要手动 Stop Timer 吗:一次超时循环改造实战
- 403浏览 收藏
-
- Golang · Go教程 | 16小时前 | 并发 · 错误处理 · go · Context · 排错 · Go 错误链 context.WithCancelCause context.Cause 取消原因
- Go context.WithCancelCause 怎么用:让中断原因能被日志和调用方看见
- 366浏览 收藏
-
- Golang · Go教程 | 17小时前 | 并发 · WaitGroup · go · worker pool · 服务停机 · Go channel WaitGroup 优雅停机 worker pool 任务排空
- Go worker pool 停机时任务为什么会丢?关闭顺序、WaitGroup 和排空策略
- 207浏览 收藏
-
- Golang · Go教程 | 19小时前 | 切片 · Slices · Go教程 · Go 1.21 · 切片删除 Go教程 Go slices.Delete slices.DeleteFunc Go 1.21
- Go slices.Delete 怎么用?删除元素后为什么一定要接收返回切片
- 463浏览 收藏
-
- Golang · Go教程 | 20小时前 | HTTP · Go教程 · 服务治理 · Shutdown · SIGTERM · SIGTERM Go 优雅关闭 http.Server Shutdown Go HTTP 服务 连接收尾 服务下线
- Go HTTP 服务优雅关闭怎么做?Shutdown、超时和连接收尾的取舍
- 316浏览 收藏
-
- Golang · Go教程 | 20小时前 | 错误处理 · Go教程 · errors.Join · errors.Is · Go 1.20 · 错误包装 errors.Is errors.As Go errors.Join 多错误处理 Go 1.20
- Go errors.Join 怎么用?多条错误合并后还能用 errors.Is 判断吗
- 431浏览 收藏
-
- Golang · Go教程 | 1天前 | Mutex · go · pprof · 性能排查 · pprof Go mutex profile Go锁竞争
- Go 服务锁竞争变慢怎么查:mutex profile 的采样、定位和修复手册
- 395浏览 收藏
-
- Golang · Go教程 | 1天前 | go · go.work · CI · Go Modules · Go go.work Go多模块 Go CI
- Go 多模块仓库怎么用 go.work:本地联调、依赖同步和 CI 一致性工作流
- 380浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ljg-skills
- ljg-skills 是李继刚开源的 AI 技能与提示词集合,面向大模型使用者整理了一批可复用的 prompt、角色设定和任务技能模板,适合用于学习提示词设计、搭建个人 AI 工作流和沉淀团队常用智能体能力。
- 4525次使用
-
- MELO音乐
- MELO音乐是一站式AI视频与音乐制作助手,对标suno, udio的高品质体验。提供伴奏生成、原创写词、无损导出、哼唱识曲、混音变声等全套音频与短视频编辑工具。无论是流行Kpop、电音说唱、民谣古风、摇滚儿歌还是商用轻音乐,MELO为你免费谱曲,轻松做同款!
- 4201次使用
-
- UniScribe
- UniScribe 是一款 AI 音视频转文字与内容整理工具,支持上传音频、视频文件或粘贴 YouTube 链接,自动生成转写文本、摘要、思维导图和关键问题,并支持多格式导出,适合会议记录、课程学习、访谈整理和内容创作复盘。
- 4162次使用
-
- 剧云
- 剧云是专业中文剧本创作平台,安全稳定运行十余年,集成AI编剧、剧本医生审核、人物小传、剧情关系图、大纲编写、多人协作、Word导入导出、版权管控功能,数据安全防护,轻松高效创作剧本。
- 4391次使用
-
- 万象有声
- 万象有声,一个专为有声创作者打造的新一代智能有声内容创作平台。平台提供专业的智能拆章、智能画本编辑、AI配音、AI生成音效、后期制作、智能对轨、智能审听等有声创作全流程工具,可以帮助创作者高效、低成本创作出引人入胜的有声作品。立即体验,让有声书制作更简单!
- 4335次使用
-
- Java 性能优化上线清单:从定位、改造到灰度发布
- 2026-06-11 860浏览
-
- Spring Boot 压测验证:Gatling、JMeter 与性能回归门禁
- 2026-06-11 843浏览
-
- Java NMT 非堆内存排查:Direct Buffer、线程栈与 Metaspace 分析
- 2026-06-11 826浏览
-
- Spring Boot 容器内存优化:JVM 堆、非堆与 MaxRAMPercentage
- 2026-06-11 809浏览
-
- Tomcat 连接与线程参数调优:maxThreads、acceptCount 与 KeepAlive
- 2026-06-11 792浏览

