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")) router.GET("/login.html", login) a := router.Group("/api/v1") { a.GET("/login", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/login.html") }) 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) { if verifyLogin(c) { c.Redirect(http.StatusTemporaryRedirect, "/api/v1/hello") return } 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" { c.AbortWithStatus(http.StatusUnauthorized) return } // Create token token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "usr": "jan", "name": "Jan Bader", "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) } maxAge := (int)((expiration * time.Hour).Seconds()) c.SetCookie("authentication", t, maxAge, "", "", false, true) c.JSON(http.StatusOK, map[string]string{ "token": t, }) return }