I am working on a Golang
Api based on Gin Framework , this Api has a method of authentication using jwt
(json web tokens)
i have the frontend client which is written in javascript (ajax,jquery)
i have to do a login with a POST method
it generates me the token
based on the email and the password from the inputs in front end ,
This is working perfectly in postman
with login endpoints and get after to the hello endpoints(private endpoints)
but in the browser it gives me an error.
The error is :Response for preflight has invalid HTTP status code 401
This error i got it just from the browser (Chrome) , but it is working at Postman
i have fixed the problem for CORS by adding an extention in the browser but it is not working by giving me the error
Could you please help here?? , thanks indeed for any help or suggestions.
Here is the client side :
<html>
<link rel="stylesheet" href="test.css">
<body>
<form id ="form" method="POST">
<p>Email:</p><br>
<input type="text" id="email" placeholder="body" /><br>
<p>Password:</p><br>
<input type="text" id="password" placeholder="body" />
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
var username;
var password;
$("#form").submit(function(e) {
var url = "http://localhost:1234/login";
var url1= "http://localhost:1234/v1/hello";
var data;// the script where you handle the form input.
var jwttoken;
username=$('#username').val();
password=$('#password').val();
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({
// Those property names must match the property names of your PromotionDecision view model
username:username,
password: password}),
success: function(data)
{
console.log(data);
window.localStorage.setItem('token', data.token);
console.log(window.localStorage.getItem('token'));
$.ajax({
type: "GET",
beforeSend: function (request)
{
request.withCredentials = true;
request.setRequestHeader("Authorization", "Bearer " + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1Mjc4NTcyOTEsImlkIjoiZWxtZWhkaS5hYXJhYkBzY2hpYnN0ZWQuY29tIiwib3JpZ19pYXQiOjE1Mjc4NTM2OTEsInJvbGUiOiJhZG1pbiJ9.wS3trHKUChsU-OmSo6tDUPPuzVriJF7z9i0_8W_36nY");
},
url: url1,
success: function(datad)
{
console.log(datad);
}
});
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
</body>
</html>
Here is the api GOLANG (Gin framework) using JWT:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
jwt "gopkg.in/appleboy/gin-jwt.v2"
"net/http"
"time"
)
func main() {
router := gin.Default()
jwtMiddleware := &jwt.GinJWTMiddleware{
Realm: "user.io",
Key: []byte("changeme"),
Timeout: time.Hour,
MaxRefresh: time.Hour,
Authenticator: authenticate,
PayloadFunc: payload,
}
router.POST("/login", jwtMiddleware.LoginHandler)
router.OPTIONS("/login", jwtMiddleware.LoginHandler)
v1 := router.Group("/v1")
v1.Use(jwtMiddleware.MiddlewareFunc())
{
v1.GET("/hello", hello)
v1.OPTIONS("/hello", hello)
}
router.Run(":1234")
}
func hello(c *gin.Context) {
fmt.Println("hello", c.Request.Header["Authorization"])
claims := jwt.ExtractClaims(c)
c.String(http.StatusOK, "id: %s
role: %s
", claims["id"], claims["role"])
}
func authenticate(email string, password string, c *gin.Context) (string, bool) {
if email == "mike@gmail.com" && password == "med" {
return email, true
}
return "", false
}
func payload(email string) map[string]interface{} {
return map[string]interface{}{
"id": "1349",
"role": "admin",
}
}