混合Web应用程序中的RESTful身份验证

时间:2015-07-27 08:41:50

标签: python rest authentication flask

我正在使用烧瓶编写混合网络应用程序。通过混合,我的意思是有传统的Web服务器应用程序使用模板引擎构建,并且还有用于客户端应用程序的RESTful API。所以这是我的困惑:

在我当前的应用程序中,用户通过Web服务器登录,以便创建HTTP会话,然后用户可以执行操作。但是,在其中一个页面中,有一个动作是通过AJAX调用同一应用程序的RESTful部分完成的。通常在此API中,用户必须再次进行身份验证。但是这里的客户端代码无法知道用户名和密码。这里的正确模式是什么?

2 个答案:

答案 0 :(得分:1)

您可以在ajax调用中验证用户客户端:

例如:

$.ajax({
     url: 'http://example.com/api.ashx/v2/users.xml',
     beforeSend: addHeaders,
     dataType: "text",
     processData: false,
     success: function(data, status) {
          // do stuff here
      },
      error: function(xhr, status, error) {
           // do stuff here
      }
 });

var addHeaders = function(xhr) {
     var restAuthHeader = readCookie("AuthorizationCookie");
     if (restAuthHeader != null) {
          xhr.setRequestHeader("Rest-Authorization-Code", restAuthHeader);
     }
 };

var readCookie = function(input) {
     var nameEQ = input + "=";
     var ca = document.cookie.split(';');
     for (var i = 0; i < ca.length; i++) {
          var c = ca[ i ];
          while (c.charAt(0) == ' ') c = c.substring(1, c.length);
          if (c.indexOf(nameEQ) == 0) 
               return c.substring(nameEQ.length, c.length);
      }
      return null;
 };

答案 1 :(得分:1)

假设您有一个包含用户名和密码的表单进行身份验证。

<form id="login-form">
  <input data-key="username" type="text" placeholder="username" />
  <input data-key="password" type="password" placeholder="password" />
  <button type="submit">Login</button>
</form>

您的端点应返回令牌和用户ID。

var $form = $('#login-form');
// post to your login endpoint with username and password
$.post('/login', {
  username: $form.find('input[data-key="username"]').val(),
  password: $form.find('input[data-key="password"]').val();
}).done(function (response) {
  // put the token and userid in the sessionStorage or localStorage
  window.sessionStorage.setItem('token', response.data.token);
  window.sessionStorage.setItem('userId', response.data.userId);
}).fail(function (e) {
  // handle incorrect credentials here.
  alert('authentication failed');
});

您应该将这些内容附加到标题中以请求数据。

function requestEndpoint(endpoint) {
  $.ajax({
    // other stuff here you probably know
    headers: {
      'X-Auth-Token': window.sessionStorage.getItem('token'),
      'X-User-Id': window.sessionStorage.getItem('userId'),
      'Content-Type': 'application/json'
    }
  });
}

只需在烧瓶中的端点扫描这些标题

相关问题