golang如何实现一个jwt授权?
package main
import (
"io"
"log"
"net/http"
"time"
"github.com/auth0/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
)
const (
APP_KEY = "golang-tech-stack.com"
)
func main() {
http.HandleFunc("/token", TokenHandler)
http.Handle("/", AuthMiddleware(http.HandlerFunc(ExampleHandler)))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func TokenHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
r.ParseForm()
username := r.Form.Get("username")
password := r.Form.Get("password")
if username != "myusername" || password != "mypassword" {
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, `{"error":"invalid_credentials"}`)
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user": username,
"exp": time.Now().Add(time.Hour * time.Duration(1)).Unix(),
"iat": time.Now().Unix(),
})
tokenString, err := token.SignedString([]byte(APP_KEY))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, `{"error":"token_generation_failed"}`)
return
}
io.WriteString(w, `{"token":"`+tokenString+`"}`)
return
}
func AuthMiddleware(next http.Handler) http.Handler {
if len(APP_KEY) == 0 {
log.Fatal("HTTP server unable to start, expected an APP_KEY for JWT auth")
}
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(APP_KEY), nil
},
SigningMethod: jwt.SigningMethodHS256,
})
return jwtMiddleware.Handler(next)
}
func ExampleHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
io.WriteString(w, `{"status":"ok"}`)
}
也可以参考:《Golang专题精进》jwt跨域鉴权