【问题标题】:Jhipster - Session Authentication Using JqueryJhipster - 使用 Jquery 的会话认证
【发布时间】:2017-01-06 03:07:49
【问题描述】:

我做了以下事情。

  • 使用 Http 会话身份验证创建 Jhipster 应用程序
  • 已启用 Cors。

我正在尝试使用 Jquery ajax 进行身份验证。但是我收到以下错误。

{
  "timestamp" : "2017-01-04T14:09:59.257+0000",
  "status" : 403,
  "error" : "Forbidden",
  "message" : "Invalid CSRF Token '16254aa2-e49d-41df-9602-ea32559617bd' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.",
  "path" : "/api/authentication"
}

我花了两天多的时间试图弄清楚如何使用 Jquery 登录。如果可以,请帮助我... :(

在我创建的用于验证身份验证的示例 HTML 下方。

<!DOCTYPE html>
<html>

  <head>
    <script src="jquery.js"></script>
    <script src="jquery-cookie.js"></script>
    <script lang="javascript">

    var domain = "127.0.0.1";


        // A $( document ).ready() block.
    $( document ).ready(function() {


        // This request will get the CSRF-TOKEN from the server and add it in the cookies

         $.ajax({
            type: 'GET',
            url:"http://"+domain+":8080/",
            success: function(data, textStatus, request){
                    console.log("Get Request fired successfully.");
            },
            error: function (request, textStatus, errorThrown) {
                    console.log(request);
                    console.log(request.getResponseHeader('Access-Control-Allow-Credentials'));
            }
        });               

                           /**
                 * Function to get the cookie
                 */
                function getCookie(name) {
                    var cookieValue = null;
                    if (document.cookie && document.cookie != '') {
                        var cookies = document.cookie.split(';');
                        for (var i = 0; i < cookies.length; i++) {
                            var cookie = jQuery.trim(cookies[i]);
                            // Does this cookie string begin with the name we want?
                            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                break;
                            }
                        }
                    }
                    console.log("Cookie Value: " + cookieValue);
                    console.log("Document Cookie Value: " + document.cookie);
                    return cookieValue;
                }  


        // This ajax setup will add the XSRF-TOKEN saved in cookies to eery POST, PUT, DELETE request.
        // You dont need the tokens for GET request.
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (settings.type == 'POST' || settings.type == 'PUT' || settings.type == 'DELETE') {

                  //  if ((/^http:.*/   //.test(settings.url) || /^https:.*/.test(settings.url))) {
                        // Only send the token to relative URLs i.e. locally.
                        xhr.setRequestHeader("X-XSRF-TOKEN", getCookie('XSRF-TOKEN'));
                  //  }
                }
            }
        }); 

    });

    // Use this function for login
    function login(){
        var url = "http://"+domain+":8080/api/authentication";
        var username = $("#username").val();
        var password = $("#password").val();

        var data = 'j_username=' + encodeURIComponent(username) +
                '&j_password=' + encodeURIComponent(password) + '&remember-me=true'   + '&submit=Login';
        console.log("Calling Login");
         $.ajax({
            type: "POST",
            url: url,
            data: data,
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: function(){
                console.log("User logged in.");
            },
            error: function(response){
                console.log("Error in Login in.");
                console.log(response.responseText);
            }
        });       
    }





    </script>
  </head>

  <body>
    <h1>Login Example</h1>



    <div class="container">
      <label><b>Username</b></label>
      <input type="text" placeholder="Enter Username" id="username" value="admin" required>

      <label><b>Password</b></label>
      <input type="password" placeholder="Enter Password" id="password" value="admin" required>

      <button type="button" onclick="login();">Login</button>
    </div>


  </body>

</html>

【问题讨论】:

    标签: jquery ajax authentication cors jhipster


    【解决方案1】:

    错误告诉您,添加 XSRF 令牌失败。顺便说一句,这与 CORS 无关。

    正如我在代码中看到的,已经有一个 sn-p 来处理 XSRF,它说令牌无效。我猜你的令牌每次设置只获取一次,而不是每次请求,因为它必须是。

    证明每个请求都在刷新其令牌,因此您不要将过时的令牌放置到您的标头中

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      相关资源
      最近更新 更多