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 高缺失率数据如何选择填充方式
    • ¥50 potsgresql15备份问题
    • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
    • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
    • ¥60 pb数据库修改与连接
    • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
    • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
    • ¥20 神经网络Sequential name=sequential, built=False
    • ¥16 Qphython 用xlrd读取excel报错
    • ¥15 单片机学习顺序问题!!