package main import ( "net/http" "time" "github.com/dgrijalva/jwt-go" "gopkg.in/gin-gonic/gin.v1" ) const ( expiration = 72 secret = "uditapbzuditagscwxuqdflgzpbu´ßiaefnlmzeßtrubiadern" ) func main() { router := gin.Default() router.LoadHTMLGlob("./templates/*") // Middleware //e.Use(middleware.Logger()) //e.Use(middleware.Recover()) //e.Use(middleware.Static("static")) a := router.Group("/api/v1") { a.GET("/login", login) a.POST("/login", loginPost) // Unauthenticated routes a.GET("/check", func(c *gin.Context) { c.String(http.StatusOK, "Accessible") }) a.GET("/hello", func(c *gin.Context) { c.String(http.StatusOK, "Hello, World!") }) } // Restricted group r := a.Group("/restricted") { //r.Use(middleware.JWT([]byte(secret))) r.GET("", restricted) } router.Run(":1323") } func restricted(c *gin.Context) { //user, _ := c.Get("user") //.(*jwt.Token) //name := user.Claims["name"].(string) name := "jan" c.String(http.StatusOK, "Welcome "+name+"!") } func login(c *gin.Context) { c.HTML(http.StatusOK, "login.html", nil) } func loginPost(c *gin.Context) { username, _ := c.GetPostForm("username") password, _ := c.GetPostForm("password") if username == "jan" && password == "passwort" { // Create token token := jwt.New(jwt.SigningMethodHS256) // Set claims //token.Claims["name"] = "Jan Bader" //token.Claims["admin"] = true //token.Claims["exp"] = time.Now().Add(time.Hour * expiration).Unix() // Generate encoded token and send it as response. t, err := token.SignedString([]byte(secret)) if err != nil { c.AbortWithStatus(http.StatusUnauthorized) } c.SetCookie("authentication", t, (int)((expiration * time.Hour).Seconds()), "/", "localhost:8080", true, false) c.JSON(http.StatusOK, map[string]string{ "token": t, }) } c.AbortWithStatus(http.StatusUnauthorized) }