initial import

This commit is contained in:
SourceFellows
2020-08-21 06:26:40 +02:00
commit e223458dd4
423 changed files with 9871 additions and 0 deletions

View File

@ -0,0 +1,5 @@
module golang.source-fellows.com/samples/jwt/server
go 1.14
require github.com/SermoDigital/jose v0.9.2-0.20161205224733-f6df55f235c2

View File

@ -0,0 +1,2 @@
github.com/SermoDigital/jose v0.9.2-0.20161205224733-f6df55f235c2 h1:koK7z0nSsRiRiBWwa+E714Puh+DO+ZRdIyAXiXzL+lg=
github.com/SermoDigital/jose v0.9.2-0.20161205224733-f6df55f235c2/go.mod h1:ARgCUhI1MHQH+ONky/PAtmVHQrP5JlGY0F3poXOp/fA=

View File

@ -0,0 +1,27 @@
package jwt
import (
"time"
"github.com/SermoDigital/jose/crypto"
"github.com/SermoDigital/jose/jws"
)
var key = []byte("meinGeheimerSchlüssel")
func CreateToken(user string) ([]byte, error) {
claims := jws.Claims{}
claims.SetAudience("source-fellows.com")
claims.SetIssuer(user)
claims.SetExpiration(time.Now().Add(time.Minute * 10))
token := jws.NewJWT(claims, crypto.SigningMethodHS256)
return token.Serialize(key)
}
func ValidateToken(token []byte) error {
newToken, err := jws.ParseJWT(token)
if err != nil {
return err
}
return newToken.Validate(key, crypto.SigningMethodHS256)
}

View File

@ -0,0 +1,31 @@
package main
import (
"log"
"net/http"
"golang.source-fellows.com/samples/jwt/server/jwt"
)
func handle(res http.ResponseWriter, req *http.Request) {
token, err := jwt.CreateToken()
if err != nil {
log.Fatal(err)
res.WriteHeader(http.StatusInternalServerError)
return
}
err = jwt.ValidateToken(token)
if err != nil {
log.Fatal(err)
res.WriteHeader(http.StatusInternalServerError)
return
}
res.Write(token)
}
func main() {
http.HandleFunc("/", handle)
http.ListenAndServe(":8080", nil)
}