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
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'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. I am using JWT method to authenticate the logged in users in the system. The product is developed on Go on the backend with gin framework for routing.
Problem
When a user log in then its JWT token is generated and works well. Now the user did not logged out but closed the browser tab or window. Before he is back, the go app is re-installed with install command. Now the user come back and access his account, the token is expired and he could not see any of his details.
Following is the code to generate token while login:
func CreateToken(user models.User, c *gin.Context) (string, error){
var ip, userAgent string
keyError := 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 * 8760).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
}
func InitKeys()(err error){
SignKey, err = ioutil.ReadFile(GetBasePath()+PrivateKeyPath)
if err != nil {
return err
}
VerifyKey, err = ioutil.ReadFile(GetBasePath()+PublicKeyPath)
if err != nil {
return err
}
return nil
}
Now to decode and match the token following function is used:
func ParseJWTToken(c *gin.Context){
merchantDb := models.MerchantDatabase{ c.Keys["merchant_db"].(string) }
merchantDatabase := make(map[string]interface{})
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,
err,
}
controllers.GetResponse(c, response)
c.Abort()
}else{
var userAgent string
var userAgentCheck bool
if values, _ := c.Request.Header["User-Agent"]; len(values) > 0 {
userAgent = values[0]
}
_ = config.InitKeys()
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 == "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 && 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,
"Missing Authorization Header",
}
controllers.GetResponse(c, response)
c.Abort()
}
}
I am not able to detect what I am missing. Please look into the code and guide me what should I do in this case.
I am using colly framework for scraping the website. Am trying to login the Evernote account for scraping some things. But I can't go through it. I used "username" and "password" titles for giving the credentials. Is this the right way ?.
Thank you in advance.
package main
import (
"log"
"github.com/gocolly/colly"
)
func main() {
// create a new collector
c := colly.NewCollector()
// authenticate
err := c.Post("https://www.evernote.com/Login.action",
map[string]string{"username":
"XXXXXX#XXX.com", "password": "*********"})
if err != nil {
log.Fatal("Error : ",err)
}
// attach callbacks after login
c.OnResponse(func(r *colly.Response) {
log.Println("response received", r.StatusCode)
})
// start scraping
c.Visit("https://www.evernote.com/")
}
You should try to mimic the browser behavior, take a look at this implementation, I've added comments on each step:
package evernote
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strings"
)
const (
evernoteLoginURL = "https://www.evernote.com/Login.action"
)
var (
evernoteJSParamsExpr = regexp.MustCompile(`document.getElementById\("(.*)"\).value = "(.*)"`)
evernoteRedirectExpr = regexp.MustCompile(`Redirecting to <a href="(.*)">`)
errNoMatches = errors.New("No matches")
errRedirectURL = errors.New("Redirect URL not found")
)
// EvernoteClient wraps all methods required to interact with the website.
type EvernoteClient struct {
Username string
Password string
httpClient *http.Client
// These parameters persist during the login process:
hpts string
hptsh string
}
// NewEvernoteClient initializes a new Evernote client.
func NewEvernoteClient(username, password string) *EvernoteClient {
// Allocate a new cookie jar to mimic the browser behavior:
cookieJar, _ := cookiejar.New(nil)
// Fill up basic data:
c := &EvernoteClient{
Username: username,
Password: password,
}
// When initializing the http.Client, copy default values from http.DefaultClient
// Pass a pointer to the cookie jar that was created earlier:
c.httpClient = &http.Client{
Transport: http.DefaultTransport,
CheckRedirect: http.DefaultClient.CheckRedirect,
Jar: cookieJar,
Timeout: http.DefaultClient.Timeout,
}
return c
}
func (e *EvernoteClient) extractJSParams(body []byte) (err error) {
matches := evernoteJSParamsExpr.FindAllSubmatch(body, -1)
if len(matches) == 0 {
return errNoMatches
}
for _, submatches := range matches {
if len(submatches) < 3 {
err = errNoMatches
break
}
key := submatches[1]
val := submatches[2]
if bytes.Compare(key, hptsKey) == 0 {
e.hpts = string(val)
}
if bytes.Compare(key, hptshKey) == 0 {
e.hptsh = string(val)
}
}
return nil
}
// Login handles the login action.
func (e *EvernoteClient) Login() error {
// First step: fetch the login page as a browser visitor would do:
res, err := e.httpClient.Get(evernoteLoginURL)
if err != nil {
return err
}
if res.Body == nil {
return errors.New("No response body")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
err = e.extractJSParams(body)
if err != nil {
return err
}
// Second step: we have extracted the "hpts" and "hptsh" parameters
// We send a request using only the username and setting "evaluateUsername":
values := &url.Values{}
values.Set("username", e.Username)
values.Set("evaluateUsername", "")
values.Set("analyticsLoginOrigin", "login_action")
values.Set("clipperFlow", "false")
values.Set("showSwitchService", "true")
values.Set("hpts", e.hpts)
values.Set("hptsh", e.hptsh)
rawValues := values.Encode()
req, err := http.NewRequest(http.MethodPost, evernoteLoginURL, bytes.NewBufferString(rawValues))
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("x-requested-with", "XMLHttpRequest")
req.Header.Set("referer", evernoteLoginURL)
res, err = e.httpClient.Do(req)
if err != nil {
return err
}
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return err
}
bodyStr := string(body)
if !strings.Contains(bodyStr, `"usePasswordAuth":true`) {
return errors.New("Password auth not enabled")
}
// Third step: do the final request, append password to form data:
values.Del("evaluateUsername")
values.Set("password", e.Password)
values.Set("login", "Sign in")
rawValues = values.Encode()
req, err = http.NewRequest(http.MethodPost, evernoteLoginURL, bytes.NewBufferString(rawValues))
if err != nil {
return err
}
req.Header.Set("Accept", "text/html")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("x-requested-with", "XMLHttpRequest")
req.Header.Set("referer", evernoteLoginURL)
res, err = e.httpClient.Do(req)
if err != nil {
return err
}
// Check the body in order to find the redirect URL:
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return err
}
bodyStr = string(body)
matches := evernoteRedirectExpr.FindAllStringSubmatch(bodyStr, -1)
if len(matches) == 0 {
return errRedirectURL
}
m := matches[0]
if len(m) < 2 {
return errRedirectURL
}
redirectURL := m[1]
fmt.Println("Login is ok, redirect URL:", redirectURL)
return nil
}
After you successfully get the redirect URL, you should be able to send authenticated requests as long as you keep using the HTTP client that was used for the login process, the cookie jar plays a very important role here.
To call this code use:
func main() {
evernoteClient := NewEvernoteClient("user#company", "password")
err := evernoteClient.Login()
if err != nil {
panic(err)
}
}
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