阅读 305

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 的真实性. 可以使用不同算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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进行简单权限认证的实现的文章就介绍到这了

原文链接:https://blog.csdn.net/qq_30505673/article/details/88750279

服务器评测 http://www.cncsto.com/ 

服务器测评 http://www.cncsto.com/ 

站长资源 https://www.cscnn.com/ 

小鱼创业 https://www.237fa.com/ 


文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐