dongyoucha0645 2018-06-01 14:13
浏览 70

。$ ajax()方法GET端点api GOLANG JWT对预检的响应具有无效的HTTP状态代码401

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",
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog