最近开发的项目涉及到login后生成token验证,同时还要传递userID,用于页面跳转后进行权限校验,流程如下:
下面直接上代码:
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.ServeFile(w, r, "tmpl/login.html")
return
}
// grab user info from the submitted form
userid := r.FormValue("usrid")
password := r.FormValue("psw")
log.Println(userid)
var creds = &Credentials{
usrid: userid,
psw: password,
}
// query database to get match username
var user User
err = db.QueryRow("SELECT user_id, user_password FROM users WHERE user_id=?",
userid).Scan(&user.User_id, &user.User_password)
checkInternalServerError(err, w)
// validate password
err = bcrypt.CompareHashAndPassword([]byte(user.User_password), []byte(password))
if err != nil {
http.Redirect(w, r, "/login", 301)
fmt.Println(err)
}
// Declare the expiration time of the token
// here, we have kept it as 10 minutes
expirationTime := time.Now().Add(10 * time.Minute)
// Create the JWT claims, which includes the username and expiry time
claims := &Claims{
Username: creds.usrid,
StandardClaims: jwt.StandardClaims{
// In JWT, the expiry time is expressed as unix milliseconds
ExpiresAt: expirationTime.Unix(),
},
}
// Declare the token with the algorithm used for signing, and the claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Create the JWT string
tokenString, err := token.SignedString(jwtKey)
if err != nil {
// If there is an error in creating the JWT return an internal server error
w.WriteHeader(http.StatusInternalServerError)
http.Redirect(w, r, "/login", 500)
fmt.Println(err)
return
}
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: tokenString,
Expires: expirationTime,
})
http.Redirect(w, r, "/list", 301)
}
//
func listHandler(w http.ResponseWriter, r *http.Request) {
//获取cookie
cookie, err := r.Cookie("token")
if err != nil {
if err == http.ErrNoCookie {
// If the cookie is not set, return an unauthorized status
w.WriteHeader(http.StatusUnauthorized)
return
}
// For any other type of error, return a bad request status
w.WriteHeader(http.StatusBadRequest)
return
}
//获取token
tokenStr := cookie.Value
claims := &Claims{}
tkn, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
log.Println("token str is ", tokenStr)
log.Println("the tkn is ", tkn)
if tkn.Valid {
log.Println("the expire time is ", claims.ExpiresAt)
}
//获取userID
username := claims.Username
fmt.Println(username)
rows, err := db.Query("SELECT * FROM cost")
checkInternalServerError(err, w)
var funcMap = template.FuncMap{
"multiplication": func(n float64, f float64) float64 {
return n * f
},
"addOne": func(n int) int {
return n + 1
},
}
var costs []Cost
var cost Cost
for rows.Next() {
err = rows.Scan(&cost.Id, &cost.Request_type,
&cost.Field, &cost.Description, &cost.Creator, &cost.Start_time)
checkInternalServerError(err, w)
costs = append(costs, cost)
}
t, err := template.New("list.html").Funcs(funcMap).ParseFiles("tmpl/list.html")
checkInternalServerError(err, w)
err = t.Execute(w, costs)
checkInternalServerError(err, w)
}