appleboy / gin-jwt Goto Github PK
View Code? Open in Web Editor NEWJWT Middleware for Gin framework
License: MIT License
JWT Middleware for Gin framework
License: MIT License
Thanks for creating this great jwt middleware. Authenticator func is only called by LoginHandler(). If I want to write MyOwnLoginhandler() where I create my own claims and signing, I wouldn't need to set Authenticator then, but it is requirement set in the MiddlewareInit(). Right now I set Authenticator to return "", true.
Question... Would moving the check for Authenticator == nil in MiddlewareInit() to the LoginHandler() function be better suited? or maybe making this field optional? That way its not a hard requirement for those who wouldn't use LoginHandler.
loginhandler Reply will be of the form {"token": "TOKEN", "expire": "xxx-xx"}, how about add a code to it, just like when we failed on authrention
I would like to access the current identity of the authenticated user in an authenticated route what is the procedure for doing this (it seems like this is not documented)?
HI i have a BAAS that i built using your gin-jwt to authenticate routes. It works just fine in localhost,
running it using "go run server.go" , However when i build it using docker i get this error message.
src/work/xprincipia/backend/gin/jwt.go:34: cannot use func literal (type func(string, string, *"gopkg.in/gin-gonic/gin.v1".Context) (string, bool)) as type func(string, string, *"github.com/gin-gonic/gin".Context) (string, bool) in field value
src/work/xprincipia/backend/gin/jwt.go:38: cannot use func literal (type func(string, "gopkg.in/gin-gonic/gin.v1".Context) bool) as type func(string, "github.com/gin-gonic/gin".Context) bool in field value
src/work/xprincipia/backend/gin/jwt.go:44: cannot use func literal (type func("gopkg.in/gin-gonic/gin.v1".Context, int, string)) as type func("github.com/gin-gonic/gin".Context, int, string) in field value
It's wierd because, I didn't get this error last week. Anyways, was it a new update that caused this. Any help would be appreciated
// the jwt middleware
var authMiddleware = &jwt.GinJWTMiddleware{
Realm: "test zone",
Key: []byte("secret key"),
Timeout: time.Hour,
MaxRefresh: time.Hour,
Authenticator: func(userId string, password string, c *gin.Context) (string, bool) {
user := gorm.User{}
passwordBytes := []byte(password)
if user.GetUserByUsername(userId) {
hashedPassword := user.HashedPassword
err := bcrypt.CompareHashAndPassword(hashedPassword, passwordBytes)
if err == nil {
glog.Info("USER LOG IN SUCCESSFUL...")
return userId, true
}
glog.Info(err)
}
return userId, false
},
Authorizator: func(userId string, c *gin.Context) bool {
//check if this user is in the db based on the jwt
return gorm.IsUserinDBbyUsername(userId)
},Unauthorized: func(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{
"code": code,
"message": message,
})
},
// TokenLookup is a string in the form of "<source>:<name>" that is used
// to extract token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "cookie:<name>"
TokenLookup: "header:Authorization",
// TokenLookup: "query:token",
// TokenLookup: "cookie:token",
}
Here is jwt.go
Hey, I'm new to JWT and Go in general. I'm confused as to what a Realm
is in the context of JWT's. I've looked everywhere I could and gin-jwt
seems to be the only place that references Realms. Could someone explain it to me?
Hi,
The JWT implementation library you use (https://github.com/dgrijalva/jwt-go) has recently introduced some changes that break some parts of your libary. I think it's just one change (token.Claims is not a map[string]interface{} anymore, but an own type of the dgrijalva library (https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md). It would be really great if you could fix this.
Thanks in advance!
Is it a good practice to allow the lookup having multiple methods instead of a single method only ?
I'm not convinced this is even an issue. Feel free to disregard.
The LoginHandler function and GinJWTMiddleware function signatures are a little misleading.
For example:
Authenticator
has a parameter named userID
, but it is passed the loginVals.Username
.PayloadFunc
has a parameter named userID
, but it is passed the loginVals.Username
, even if the Authenticator function returns a user id.Authorizator
has a parameter named userID
, and it is passed the userID (not the username) which I think is correct, but different from the way other functions are being called.It is pretty minor. Just wanted to let you know there was a little friction getting started. It might also be tricky to change any of this without breaking backwards compatibility.
Thanks for the great work!
Hi,
I get a signature error while using it with the gin package "gopkg.in/gin-gonic/gin.v1"
However If i change gin-jwt gin import from "github.com/gin-gonic/gin"
to "gopkg.in/gin-gonic/gin.v1"
it works.
What's the best practice here ?
gin-jwt v1
for jwt-go v2
gin-jwt v2
for jwt-go v3
.\main.go:50: cannot use Authenticator (type func(string, string, *"j99.io/app/cloud_token_api/vendor/github.com/gin-gonic/gin".Context) (string, bool)) as type func(string, string, *"github.com/gin-gonic/gin".Context) (string, bool) in field value
.\main.go:51: cannot use Authorizator (type func(string, *"j99.io/app/cloud_token_api/vendor/github.com/gin-gonic/gin".Context) bool) as type func(string, *"github.com/gin-gonic/gin".Context) bool in field value
.\main.go:52: cannot use Unauthorized (type func(*"j99.io/app/cloud_token_api/vendor/github.com/gin-gonic/gin".Context, int, string)) as type func(*"github.com/gin-gonic/gin".Context, int, string) in field value
.\main.go:81: cannot use authMiddleware.LoginHandler (type func(*"github.com/gin-gonic/gin".Context)) as type "j99.io/app/cloud_token_api/vendor/github.com/gin-gonic/gin".HandlerFunc in argument to app.RouterGroup.POST
in jwtFromHeader method, auth header must be "Bearer", can customize it when init ( add more to TokenLookup ?)
At the moment the Authenticator has the following signature: func(username string, password string, c *gin.Context).
This works perfectly when you only have a username/password that you'd like to auth on. In our use case we have a username/password but also need to auth an OTP.
Even though the GIN context is being passed down to the Authenticator one does not have access to the c.Request.Body if you wanted to manually parse out any extra params because the c.Request.Body has already been read and cleared by the time it gets to the Authenticator.
It would be preferable to do the auth in one request instead of first getting a JWT token and then doing the OTP auth separate.
Is additional parameter handling a feature that can be added to gin-jwt or is this something that I need to try and fudge in using middleware that copies the c.Request.Body and records it in the context?
I found this article How to revoke a valid token?
Is there a way to revoke it?
I try refresh token, but failed.
how to do ?
Need fix Readme or code, example/server.go imports "github.com/appleboy/gin-jwt" and i don't have it because
Install gin-gwt v2 version for jwt-go v3 version. To get the package, execute:
$ go get gopkg.in/appleboy/gin-jwt.v2
And how does it work? Seems like a few functions are really badly documented.
Is there any way to set token in cookie when authenticator callback fired?
I'm trying to just get session information into my handlers. For that I want a route to be accessible by authorised users as well as guests. Can gin_jwt
library handle this situation? I'm not sure how to avoid the auth header empty
error.
Hi, @appleboy
last tag v2.1.1
, you use github.com/gin-gonic/gin
, but the latest v2.1.2
you use gopkg.in/gin-gonic/gin.v1
, the change will broke the program who use github.com/gin-gonic/gin
I am currently dealing with the problem of fetching the username in the auth route group.
How do I do that?
Hi thanks for this.
I'm using this middleware but can't help notice the typo here. Thanks!
https://github.com/appleboy/gin-jwt/blob/master/auth_jwt.go#L143
How do I access the JWT payload? Nothing seems to work and it isn't documented. #23 didn't work.
Hi,
(thx for having merged so quickly my PR on Context injection ^^)
I'm facing an issue, and I think it may be a functional / logical problem in Authorization implementation and / or limitations cause by lack of informations about groups in gin.Context.
For example, here are my groups definitions for admin/users :
admin := r.Group("/admin")
admin.Use(authMiddleware.MiddlewareFunc())
{
users := admin.Group("/users")
users.GET("/:username", user.ByUsernameHandler)
users.POST("", registration.RegisterHandler)
users.GET("", user.AllUsersHandler)
}
By using your Authorizator callback, I have to be aware of two informations :
Each leads me to an issue :
Should I implement my own solution like writing a specific Middleware, with an string argument telling me what group is called ? Or is there any more elegant way to fix this ?
functionality request, say multiple scheme,
'''
TokenLookup: "header:Authorization|query:token",
'''
I want the user to be logged out after a week of not using the site. How can I do this?
It should be "http -v --json POST localhost:8000/login username=admin password=admin", or "curl -v -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"admin"}' localhost:8000/login"
I'm trying to access the current userId from a very simple /me route returning the currently logged user informations. I've read in your code that it's supposed to be set at the key "userId" in c, but c.Get("userId") tells me it doesn't exist in my context. What am I doing wrong ?
in main :
auth := r.Group("/users")
auth.Use(authMiddleware.MiddlewareFunc())
{
auth.GET("/me", user.Me)
auth.GET("/refresh_token", authMiddleware.RefreshHandler)
}
my handler :
func Me(c *gin.Context) {
username, exists := c.Get("userId")
log.Print(username) //return nil
log.Print(exists) //return false
}
Thx !
Hi ,
Im trying to run the refresh token handler and it`s get panic on the converting of
origIat := int64(token.Claims["orig_iat"].(float64))
It look like the claim is nill.
`
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] POST /login --> gopkg.in/appleboy/gin-jwt%2ev1.(*GinJWTMiddleware).LoginHandler-fm (3 handlers)
[GIN-debug] GET /auth/hello --> main.HelloHandler (4 handlers)
[GIN-debug] GET /auth/refresh_token --> gopkg.in/appleboy/gin-jwt%2ev1.(*GinJWTMiddleware).RefreshHandler-fm (4 handlers)
2947 :8000
�[31m2016/07/04 18:24:56 [Recovery] panic recovered:
GET /auth/refresh_token HTTP/1.1
Host: localhost:8000
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,he;q=0.6
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0Njc2NDg3ODIsImlkIjoiYWRtaW4ifQ.HD_0Lx9UGF3yQMJZCvbPadB7_rKVdtaPD-vIqH4FA-o
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json
Dnt: 1
Postman-Token: 27f71581-af40-e08a-30d8-ddd81e89247a
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
interface conversion: interface is nil, not float64
/usr/local/go/src/runtime/panic.go:423 (0x42a2c9)
gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/usr/local/go/src/runtime/iface.go:218 (0x40d3f5)
assertE2T: panic(&TypeAssertionError{"", "", *t._string, ""})
/home/mik/go-programes/src/gopkg.in/appleboy/gin-jwt.v1/auth_jwt.go:199 (0x49a81e)
(*GinJWTMiddleware).RefreshHandler: origIat := int64(token.Claims["orig_iat"].(float64))
`
I have a problem posting on postman, my headers are Content-Type: application/json and my body (I've tested both form-data and form-url-encoded) key=value are: username: chaofanman password:password and it doesn't work. I always get {"code":400,"message":"Missing Username or Password"}. However, when i post using httpie it is totally find. It also works on raw as a json however. What am i doing wrong?
Hi All, I'm trying to include the logged user info into Gin Default Log, but Go won't allow me to include the gin-jwt import into logger.go file, because it creates "import cycle".
Has anyone faced this?
Thanks in Advance.
Hi, I set Timeout and MaxRefresh all to 1 minutes,when token expired after one minute,I use old token in the header and request refresh_token api but still return expired.
If I use ajax to request my api, but found token expired,ajax need request refresh_token to get a new one,but response said expired,so how to resolve it?? thx!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.