-
Notifications
You must be signed in to change notification settings - Fork 390
Description
Problem
- DRY Code: The
SetCookie
code is redundant we’ve duplicated the logic for setting cookies in both theLoginHandler
andRefreshToken
. - We do have the
func (*GinJWTMiddleware) TokenGenerator
method for clients to generateJWT
tokens independently of theLoginHandler
orRefreshToken
methods. However, without a dedicatedSetCookie
method, cookie setting remains tightly coupled with these methods. Introducing aSetCookie
method would enhance scalability by enabling cookies to be set independently, eliminating the need for manual cookie handling where such functionality is currently absent.
Context:
This library looks very useful for us. However at the moment I don't think it supports oauth
? Basically I don't want my users to register with a username/password, but instead I'd like them to use SSO, maybe provided by Facebook, Google or our built inhouse elitmus.com. Once the oauth flow is complete, I'd like to use my own JWT tokens though. I'd like to use the user info I get from SSO to build the token.
So far I have something like this:
I am using the TokenGenerator
method to generate the jwt
token
tokenString, expire, err := auth.TokenGenerator(&User)
And in our case we want to store the token in the cookie and we don't have an method to do that. As that method is tightly coupled with the LoginHandler
method.
To make the method to set the cookie for us I have written the method in our application code.
type GinJWTMiddleware struct {
*jwt.GinJWTMiddleware
}
func NewAuthMiddleware() (*jwt.GinJWTMiddleware, error) {
...
}
func (mw *GinJWTMiddleware) SetCookie(c *gin.Context, tokenString string) {
if mw.SendCookie {
expireCookie := mw.TimeFunc().Add(mw.CookieMaxAge)
maxage := int(expireCookie.Unix() - mw.TimeFunc().Unix())
if mw.CookieSameSite != 0 {
c.SetSameSite(mw.CookieSameSite)
}
c.SetCookie(
mw.CookieName,
tokenString,
maxage,
"/",
mw.CookieDomain,
mw.SecureCookie,
mw.CookieHTTPOnly,
)
}
}
Solution Implementation:
SetCookie
Method: This method is added to the*GinJWTMiddleware
and is responsible for setting the cookie in the response. It takes the context, token as parameters.- Refactored
LoginHandler
andRefreshToken
: Both methods now callSetCookie
to set the cookie, eliminating the duplicated logic and centralizing cookie handling in one place.