I'm stuck on getting sessions to work in GoLang. Specifically within Iris.
Calling a route with "Login" will print out a token; then when I call a route with Restricted, the token is empty. Am I doing something wrong or do I misunderstand the concept behind sessions in GoLang?
func Login(c *iris.Context) {
username := c.FormValueString("email")
password := c.FormValueString("password")
test := "unauthorized"
if username == "jon#snow.com" && password == "123abc!##" {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"name": "Jon Snow",
"exp": time.Now().Add(time.Hour * 72).Unix(),
})
t, err := token.SignedString([]byte("SecretKey"))
if err != nil {
panic(err)
}
c.Session().Set("token", t)
test = c.Session().GetString("token")
}
c.Text(200, test)
}
func Restricted(c *iris.Context) {
tokenString := c.Session().GetString("token")
if tokenString != "" {
c.Text(iris.StatusOK, tokenString)
} else {
c.Text(iris.StatusOK, "no Token")
}
}
You should import the session package first go get "github.com/kataras/iris/sessions"
then create a session with var sess = sessions.New(sessions.Config{Cookie: "cookie-name" })read this documentation to see how this work
Related
I have the following function to create a server side HTTPOnly with gofiber framework using the v2 version "github.com/gofiber/fiber/v2"
func Signin(c *fiber.Ctx) error {
type SigninData struct {
Email string `json:"email" xml:"email" form:"email"`
Password string `json:"password" xml:"password" form:"password"`
}
data := SigninData{}
if err := c.BodyParser(&data); err != nil {
return err
}
var user models.User
findUser := database.DB.Where("email = ?", data.Email).First(&user)
if findUser == nil {
c.Status(fiber.StatusBadRequest)
return c.JSON(fiber.Map{
"message": "Account not found",
})
}
if err := user.ComparePassword(data.Password); err != nil {
c.Status(fiber.StatusBadRequest)
return c.JSON(fiber.Map{
"message": "Invalid credentials",
})
}
isSuperuser := database.DB.Where("email = ? AND is_superuser = ?", data.Email, true).First(&user).Error
var scope string
if errors.Is(isSuperuser, gorm.ErrRecordNotFound) {
scope = "user"
} else {
scope = "admin"
}
token, err := middlewares.CreateTokens(user.Email, scope)
if err != nil {
c.Status(fiber.StatusBadRequest)
return c.JSON(fiber.Map{
"message": "Could not generate session tokens",
})
}
saveErr := middlewares.RedisStoreTokens(user.Email, token)
if saveErr != nil {
c.Status(fiber.StatusBadRequest)
return c.JSON(fiber.Map{
"message": "Could not save session to redis",
})
}
tokens := map[string]string{
"access_token": token.AccessToken,
"refresh_token": token.RefreshToken,
}
cookie := fiber.Cookie{
Name: "access_token",
Value: tokens["access_token"],
Expires: time.Now().Add(time.Hour * 24),
HTTPOnly: true,
Secure: true,
}
c.Cookie(&cookie)
return c.JSON(fiber.Map{
"access_token": tokens["access_token"],
"refresh_token": tokens["refresh_token"],
"token_type": "bearer",
})
}
Here is what it returned on signin
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdXVpZCI6ImFlMmQ4MDlhLTNhZDgtNDgwNS1iMjZlLWUyYWMwNTYyMjZhZiIsImF1dGhvcml6ZWQiOnRydWUsImV4cCI6MTY0MTE4NTg5MCwicGVybWlzc2lvbiI6InVzZXIiLCJzdWIiOiJ0ZXN0OEBleGFtcGxlLmNvbSJ9.cXzkNoDb1XKmt_quQ4ONvDcXfmPrBjt4umG38a1xwqA",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZWZyZXNoX3V1aWQiOiJhZTJkODA5YS0zYWQ4LTQ4MDUtYjI2ZS1lMmFjMDU2MjI2YWYrK3Rlc3Q4QGV4YW1wbGUuY29tIn0._6zOG65GmnwbWnpKaQb2LxuPIhKZGCzg9P62xoBds8U",
"token_type": "bearer"
}
cookie access_token is created with the value of eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdXVpZCI6ImFlMmQ4MDlhLTNhZDgtNDgwNS1iMjZlLWUyYWMwNTYyMjZhZiIsImF1dGhvcml6ZWQiOnRydWUsImV4cCI6MTY0MTE4NTg5MCwicGVybWlzc2lvbiI6InVzZXIiLCJzdWIiOiJ0ZXN0OEBleGFtcGxlLmNvbSJ9.cXzkNoDb1XKmt_quQ4ONvDcXfmPrBjt4umG38a1xwqA
and if one checks the payload data of the cookie one gets the following
{
"access_uuid": "ae2d809a-3ad8-4805-b26e-e2ac056226af",
"authorized": true,
"exp": 1641185890,
"permission": "user",
"sub": "test8#example.com"
}
So now i want another function that will pull and be able to grab all of these payload data within the cookie so i can use it within the app
Here is a function i have that is supposed to grab those data but things are not working and gofiber does not log any error so difficult to even troubleshoot
type ClaimsWithScope struct {
jwt.RegisteredClaims
Scope string `json:"permissions"`
}
type AccessDetails struct {
AccessUuid string `json:"access_uuid"`
Email string `json:"email"`
}
type AccessDetailsClaims struct {
jwt.RegisteredClaims
Scope string `json:"permissions"`
AccessUuid string `json:"access_uuid"`
Authorized string `json:"authorized"`
}
...
...
...
func GetAccessDetails(c *fiber.Ctx) (*AccessDetails, error) {
ad := &AccessDetails{}
cookie := c.Cookies("access_token")
var err error
token, err := jwt.ParseWithClaims(cookie, &AccessDetailsClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(SecretKey), nil
})
if err != nil {
return nil, err
}
payload := token.Claims.(*AccessDetailsClaims)
ad.Email = payload.Subject
ad.AccessUuid = payload.AccessUuid
return ad, nil
}
what am i doing wrong here? ad should be able to return the full payload data like those created from the signin function like this
{
"access_uuid": "ae2d809a-3ad8-4805-b26e-e2ac056226af",
"authorized": true,
"exp": 1641185890,
"permission": "user",
"sub": "test8#example.com"
}
so i can then be able to grab whatever data i need from it
finally figured it out
func GetAccessDetails(c *fiber.Ctx) (*AccessDetails, error) {
ad := &AccessDetails{}
cookie := c.Cookies("access_token")
var err error
token, err := jwt.Parse(cookie, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("ACCESS_SECRET")), nil
})
if err != nil {
return nil, err
}
payload := token.Claims.(jwt.MapClaims)
ad.Email = payload["sub"].(string)
ad.AccessUuid = payload["access_uuid"].(string)
return ad, nil
}
so since i used mapClaims to create the token, so i can grab it with this
token, err := jwt.Parse(cookie, func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("ACCESS_SECRET")), nil
})
and then assigns the elements of ad := &AccessDetails{} as follows
payload := token.Claims.(jwt.MapClaims)
ad.Email = payload["sub"].(string)
ad.AccessUuid = payload["access_uuid"].(string)
I have a gorm connection that I initially create by passing an AWS authentication token that expires every 15 minutes. The service will be able to connect to the DB for 15 minute. I have some functions for connecting to the db, for creating a new token, and for using a cron library to "refresh" the connection. I'm stuck in knowing how to actually provide the new token to GORM. I though of just doing gorm.Open() from within the cron job, but was told this would be bad because it'd not be thread safe, and would leave the old connections open. I was directed to this but I'm not sure what to do with it:
https://golang.org/pkg/database/sql/driver/#Connector
There is an example here:
https://github.com/aws/aws-sdk-go/issues/3043#issuecomment-581931580
But I'm not sure what I'd replace the driver and connector code in that example for GORM. Anyhow.
Here's the code I have so far. First this connection function that wraps around gorm.Open:
func Connect(conf *config.DbConfig) (*gorm.DB, error) {
host, port, err := net.SplitHostPort(conf.Host)
if err != nil {
return nil, err
}
sslMode := "require"
if conf.DisableTLS {
sslMode = "disable"
}
return gorm.Open(conf.Dialect,
fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
host, port, conf.Username, conf.Password, conf.Name, sslMode))
}
This is called in main like so:
//IF WE WANT TO USE AWS TOKEN, REPLACE PW IN CONFIG WITH TOKEN
if conf.DB.UseAwsToken {
authToken, err := field.CreateAuthToken(&conf.DB)
if err != nil {
logger.Fatal(err)
}
conf.DB.Password = authToken
}
//CONNECT TO DB
db, err := field.Connect(&conf.DB)
if err != nil {
logger.Fatal(err)
}
defer db.Close()
//INITIALIZE CRON JOB THAT RUNS IN SEPARATE THREAD TO REFRESH CONNECTION
if conf.DB.UseAwsToken {
processorCron := cron.New()
cronInterval := "#every 10m"
if conf.DB.CronInterval > 0 {
cronInterval = fmt.Sprintf("#every %s", conf.DB.CronInterval)
}
processorCron.AddFunc(cronInterval, func() {
repo.RenewDB(&conf.DB)
})
processorCron.Start()
}
The part I'm stuck with the actual code for the RenewDB function, in the spot with the TODO:
type Repo struct {
db *gorm.DB
}
// FUNCTION
func (r *Repo) RenewDB(dbConf *config.DbConfig) {
var err error
if dbConf.Password, err = CreateAuthToken(dbConf); err != nil {
panic(fmt.Sprintf("failed at createAuthToken: %s\n", err.Error()))
}
//TODO: HOW DO I UPDATE GORM TO USE THE NEW AUTH TOKEN THAT I INSERTED
// INTO dbConf?
}
//AUTH TOKEN GENERATOR
func CreateAuthToken(dbConf *config.DbConfig) (string, error) {
awsSession, err := session.NewSession()
if err != nil {
return "", err
}
authToken, errToken := rdsutils.BuildAuthToken(dbConf.Host, dbConf.AwsRegion, dbConf.Username, awsSession.Config.Credentials)
if errToken != nil {
return "", errToken
}
return authToken, nil
}
I need to decode my JWT token and check if the scope is a "Doctor".
I know very little about GO, but I just need to write a tiny snippet in my application to extend an existing application so it needs to be written in GO.
This was my attempt at decoding the token and checking if "Doctor" was in the decoded token as I wasn't able to access the scope exclusively.
for k, v := range props {
token_value := fmt.Sprint(v)
token_key := fmt.Sprint(cfg.AuthKey)
if (k == "custom_token_header") && strings.Contains(token_value, token_key) {
if token, _ := jwt.Parse(token_value, nil); token != nil {
parsed_token := fmt.Sprint(token)
log.Infof("Parsed token: " ,parsed_token)
if strings.Contains(parsed_token, "Doctor") {
log.Infof("user is a Doctor, perform checks...")
loc, _ := time.LoadLocation("GMT")
now := time.Now().In(loc)
hr, _, _ := now.Clock()
if hr >= 9 && hr < 5 {
log.Infof("success, inside of work hours!!")
return &v1beta1.CheckResult{
Status: status.OK,
}, nil
}
log.Infof("failure; outside of work hours!!")
return &v1beta1.CheckResult{
Status: status.WithPermissionDenied("Unauthorized..."),
}, nil
}
}
log.Infof("success, as you're not a doctor!!")
return &v1beta1.CheckResult{
Status: status.OK,
}, nil
}
}
It's working fine outside of my app, but when run inside my app it's being strange and giving back this <nil> map[] <nil> false for where the claims would be, but when run outside the app it gives me
map[alg:RS256 kid:NUVGODIxQThBQkY2NjExQjgzMEJEMjVBQTc3QThBNTY4QTY3MzhEMA typ:JWT] map[aud:https://rba.com/doctor azp:3XFBbjTL6tsL9wH6iZQtkz3rKgGeiLwh exp:1.55546266e+09 gty:client-credentials iat:1.55537626e+09 iss:https://jor2.eu.auth0.com/ scope:Doctor sub:3XFBbjTL6tsL9wH6iZQtkz3rKgGeiLwh#clients] false
Thanks to devdotlog I was able to get this working with this change:
for k, v := range props {
tokenString := fmt.Sprint(v)
tokenKey := fmt.Sprint(cfg.AuthKey)
if (k == "custom_token_header") && strings.Contains(tokenString, tokenKey) {
tokenString = strings.Replace(tokenString, "Bearer ", "", -1)
token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
fmt.Println(err)
return nil, nil
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
tokenScope := fmt.Sprint(claims["scope"])
log.Infof("Scope: ", tokenScope)
if tokenScope == "Doctor" {
log.Infof("user is a Doctor, perform checks...")
loc, _ := time.LoadLocation("GMT")
now := time.Now().In(loc)
hr, _, _ := now.Clock()
if hr >= 9 && hr < 5 {
log.Infof("success, inside of work hours!!")
return &v1beta1.CheckResult{
Status: status.OK,
}, nil
}
log.Infof("failure; outside of work hours!!")
return &v1beta1.CheckResult{
Status: status.WithPermissionDenied("Unauthorized..."),
}, nil
}
fmt.Println(claims["scope"])
} else {
fmt.Println(err)
}
log.Infof("success, as you're not a doctor!!")
return &v1beta1.CheckResult{
Status: status.OK,
}, nil
}
}
You use github.com/dgrijalva/jwt-go. That's right?
You use ParseUnverified(https://godoc.org/github.com/dgrijalva/jwt-go#Parser.ParseUnverified) without validation.
Below code is ParseUnverified()' example.
package main
import (
"fmt"
"github.com/dgrijalva/jwt-go"
)
func main() {
// This token is expired
var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
fmt.Println(err)
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
fmt.Println(claims["foo"], claims["exp"])
} else {
fmt.Println(err)
}
}
ParseUnverified() only use for debug.
WARNING: Don't use this method unless you know what you're doing
This method parses the token but doesn't validate the signature. It's only ever useful in cases where you know the signature is valid (because it has been checked previously in the stack) and you want to extract values from it.
I'm trying to save a logged user ID in my golang backend with gorilla sessions and securecookie.
Here is my package session :
package session
import (
"fmt"
"net/http"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(32))
//GetSessionLoggedID returns loggedID
func GetSessionLoggedID(r *http.Request) int {
storeAuth, _ := store.Get(r, "authentication")
if auth, ok := storeAuth.Values["loggedID"].(bool); ok && auth {
return storeAuth.Values["loggedID"].(int)
}
fmt.Println("none found")
return 0
}
//SetSessionLoggedID sets cookie session user ID
func SetSessionLoggedID(w http.ResponseWriter, r *http.Request, id int) {
storeAuth, err := store.Get(r, "authentication")
if err != nil {
fmt.Println(err.Error())
}
storeAuth.Options = &sessions.Options{HttpOnly: true, Secure: true, MaxAge: 2628000, Path: "/"}
storeAuth.Values["loggedID"] = id
storeAuth.Save(r, w)
}
I have another package that gets to verify email / password of a user that logs in.
Here is the function :
func (handler *UserHandler) checkPassword(w http.ResponseWriter, r *http.Request) {
var body struct {
Email string
Password string
}
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
loggedID, err := handler.UserUsecase.PasswordMatch(body.Email, body.Password)
if err != nil || loggedID == 0 {
http.Error(w, "Could not authenticate user", http.StatusUnauthorized)
return
}
session.SetSessionLoggedID(w, r, loggedID)
json.NewEncoder(w).Encode(struct {
ID int `json:"id"`
}{loggedID})
}
The ID returned is the proper one. But the session is not saving as I would have liked.
If I add a session.GetSessionLoggedID(r) at the end of checkpassword function, I get "none found".
What am I missing ?
// watch this line
if auth, ok := storeAuth.Values["loggedID"].(bool); ok && auth {
storeAuth.Values["loggedID"] is not bool, so ok is false, then you get "none found"
Change to
if auth, ok := storeAuth.Values["loggedID"]; ok{
return auth.(int)
}
fmt.Println("none found")
I am working on a SAAS based product which is built in Angular5 at front end. It uses Go's rest APIs to connect to DB and all back end functionality. I am using JWT token to authenticate the users on this system.
On the back end, I am using Gin framework for API routing and response handling.
The problem I am facing is that when ever I compile latest code on server. The token expires and it asks me to login again in order to generate new token.
The code I am using to generate JWT is given below:
package main
import (
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/contrib/sessions"
)
func CreateToken(user models.User, c *gin.Context) (string, error){
var ip, userAgent string
keyError := config.InitKeys()
if keyError != nil{
return "", keyError
}
if values, _ := c.Request.Header["Ip"]; len(values) > 0 {
ip = values[0]
}
if values, _ := c.Request.Header["User-Agent"]; len(values) > 0{
userAgent = values[0]
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.MapClaims{
"email": user.EmailId,
"exp": time.Now().Add(time.Hour * 8).Unix(),
"role": user.Role,
"name": user.FirstName+" "+user.LastName,
"ip": ip,
"user_agent": userAgent,
"id": user.Id,
})
config.CurrentUserId = user.Id
models.CurrentUser = user
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte(config.SignKey))
return tokenString, err
}
And code to compare it with the token that is being sent in the header from front end is:
if values, _ := c.Request.Header["Authorization"]; len(values) > 0 {
bearer := strings.Split(c.Request.Header["Authorization"][0], "Bearer")
bearerToken := strings.TrimSpace(bearer[1])
_, err := merchantDb.GetSession(bson.M{"token": bearerToken})
if err != nil{
errMsg := "Failed: Unauthorized Access."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
nil,
}
controllers.GetResponse(c, response)
c.Abort()
}else{
var ip, userAgent string
var ipCheck, userAgentCheck bool
if values, _ := c.Request.Header["Ip"]; len(values) > 0 {
ip = values[0]
}
if values, _ := c.Request.Header["User-Agent"]; len(values) > 0{
userAgent = values[0]
}
token, err := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {
return config.SignKey, nil
})
if len (token.Claims.(jwt.MapClaims)) > 0{
for key, claim := range token.Claims.(jwt.MapClaims) {
if key == "ip" {
if claim == ip{
ipCheck = true
}
}
if key == "user_agent"{
if claim == userAgent{
userAgentCheck = true
}
}
if key == "role"{
role = claim.(string)
}
if key == "id"{
userId = claim.(float64)
}
if key == "name"{
userName = claim.(string)
}
}
}
merchantDatabase["userid"] = userId
merchantDatabase["role"] = role
merchantDatabase["username"] = userName
c.Keys = merchantDatabase
if err == nil && token.Valid && ipCheck == true && userAgentCheck == true {
c.Next()
} else {
errMsg := "Failed: Invalid Token."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
nil,
}
controllers.GetResponse(c, response)
c.Abort()
}
}
}else{
errMsg := "Failed: Unauthorized Access."
response := controllers.ResponseController{
config.FailureCode,
config.FailureFlag,
errMsg,
nil,
}
controllers.GetResponse(c, response)
c.Abort()
}
This issue is consuming a lot of time. If issue is known to anyone, Please reply to this post.
Thanks!
I suspect, there is something wrong with your session
_, err := merchantDb.GetSession(bson.M{"token": bearerToken})
or something else, as you didn't share the full code. Perhaps, your SigningKeys are not consistent between the builds.
I wrote a small test for you to prove that jwt tokens don't expire between go builds
package main
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"time"
)
func CreateToken() (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.MapClaims{
"email": "test#email.com",
"exp": time.Now().Add(time.Hour * 240).Unix(),
//"exp": time.Now().Add(-time.Hour * 8).Unix(),
"role": "test role",
"name": "test name",
"ip": "1.1.1.1",
"user_agent": "test agent",
"id": "123",
})
// Sign and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte("AllYourBase"))
return tokenString, err
}
func main() {
//tokenString,_ := CreateToken()
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAZW1haWwuY29tIiwiZXhwIjoxNTIzNjAwOTM1LCJpZCI6IjEyMyIsImlwIjoiMS4xLjEuMSIsIm5hbWUiOiJ0ZXN0IG5hbWUiLCJyb2xlIjoidGVzdCByb2xlIiwidXNlcl9hZ2VudCI6InRlc3QgYWdlbnQifQ.UCD3P5-ua3qgTvy_-7hmHEVPPZwFCbhmRJNqndBwtes"
token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("AllYourBase"), nil
})
fmt.Println(token)
fmt.Println(token.Valid)
}
As you can check, the tokenString will be valid for the next 10 days wherever you run this code