To start this app, perform the following step in order
- Clone this repo to your machine
- cd into the project folder
- enter
go run main.go
to start server
Getting through the basics of setting up an authentication in Golang.
I Implemented the Jwt-Middleware (JwtVerify(...)) the same way as you did:
func JwtVerify(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var tk = r.Header.Get("x-access-token") // Grab the token from the header
tk = strings.TrimSpace(tk)
if tk == "" {
// Token is missing, returns with error code 403 Unauthorized
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(Exception{Message: "Missing auth token"})
return
}
claims := &models.Token{}
_, err := jwt.ParseWithClaims(tk, claims, func(token *jwt.Token) (interface{}, error) {
return []byte("secret"), nil
})
if err != nil {
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(Exception{Message: err.Error()})
return
}
ctx := context.WithValue(r.Context(), "user", claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
When I run the program, the following error occurs:
auth/middleware.go:30:45: cannot use func literal (type func(*jwt.Token) (interface {}, error)) as type jwt.Keyfunc in argument to jwt.ParseWithClaims
My IDE also shows an error:
Cannot use 'func(token *jwt.Token) (interface{}, error)' (type func(token *jwt.Token) (interface{}, error)) as type Keyfunc
I have imported the JWT (and all other packages) via Dep.
Have you come across this problem before?
Thank you & best regards
user.go -> FindOne
actually not working properly.
It drops the error:
crypto/bcrypt: hashedSecret too short to be a bcrypted password
in function
errf := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
It's because of current User model doesn't save Password with correct size.
And actually when you check only bcrypt.ErrMismatchedHashAndPassword type of error,
it allow to go through authentication using any password.
If do edit for User model in Password field - CompareHashAndPassword works correct.
//User struct declaration
type User struct {
gorm.Model
Name string
Email string `gorm:"type:varchar(100);unique_index"`
Password string `gorm:"size:100" json:"Password"`
Role string `json:"Role"`
Rovers string `json:"Rovers"`
}
In user.go
function UpdateUser
saves not hashed password to DB.
So, it should look something like this:
func UpdateUser(w http.ResponseWriter, r *http.Request) {
user := &models.User{}
params := mux.Vars(r)
var id = params["id"]
db.First(&user, id)
json.NewDecoder(r.Body).Decode(user)
pass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
fmt.Println(err)
err := ErrorResponse{
Err: "Password Encryption failed",
}
json.NewEncoder(w).Encode(err)
}
user.Password = string(pass)
db.Save(&user)
json.NewEncoder(w).Encode(&user)
}
Sorry for posting like this) Sometime I will have a time to post some PR.
when i send a post request to create users i am getting this msg at the server end
curl -d POST http://10.10.20.51:8000/register{"username":"john","email":"johndoe","Gender":"m","Password":"mysecurepassword",} 404 page not found
404 page not found
404 page not found
404 page not found
{"Value":{"ID":0,"CreatedAt":"2021-09-07T15:42:34.436458891+05:30","UpdatedAt":"2021-09-07T15:42:34.436458891+05:30","DeletedAt":null,"Name":"","Email":"","Gender":"","Password":"$2a$10$8vhtNxUKXqF87gum4xw44O9xg7bPv3XvRpLSQDc9f3H2X8y.0lCmK"},"Error":{},"RowsAffected":0}
[root@localhost ~]#
this the post response i am getting is the post request format wrong??
I'm new to Go, so I may be missing something obvious, but after following the three-line instructions, the go interpreter tells me it can't find auth/routes
124 golang-jwt-authentication-master $ go run main.go
main.go:4:2: cannot find package "auth/routes" in any of:
$GOPATH/src/github.com/unquabain/golang-jwt-authentication-master/vendor/auth/routes (vendor tree)
/usr/local/Cellar/go/1.13.1/libexec/src/auth/routes (from $GOROOT)
$GOPATH/src/auth/routes (from $GOPATH)
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.