【问题标题】:how to send authenticated ajax call to web API如何将经过身份验证的 ajax 调用发送到 Web API
【发布时间】:2015-07-24 16:03:22
【问题描述】:

我有一个 Web Api 应用程序,它有以下问题。

 [HttpGet]
    [Route("Account/userName{userName}/password={password}/rememberMe/{rememberMe}")]
    public HttpResponseMessage LogIn(string userName, string password, bool rememberMe)
    {
        if (User.Identity.IsAuthenticated)
        {
            return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in.");
        }

        var dbPerson = dbContext.Persons.Where(x => x.UserName.Equals(userName) && x.EncryptedPassword.Equals(password)).FirstOrDefault();
        if (dbPerson != null)
        {
            FormsAuthentication.SetAuthCookie(userName, rememberMe);
            return Request.CreateResponse(HttpStatusCode.OK, "logged in successfully");
        }
        else
        {
            return new HttpResponseMessage(HttpStatusCode.Unauthorized);
        }
    }

我从另一个 MVC 项目中调用。我得到了身份验证,但在下一页我正在调用 ajax 方法

var uri = 'http://localhost:44297/api/XXXX';

$(document).ready(function () {
  // Send an AJAX request
  $.getJSON(uri)
      .done(function (data) {
        // On success, 'data' contains a list of products.

          for (var i = 0; i < data.$values.length; i++)
          {      


             }
    })
    .fail(function() {
        console.log( "error" )});


});

我收到 GET http://localhost:44297/api/StudyFocus 401(未经授权)。我该如何解决这个问题。我知道我需要通过这个 ajax 调用传递一些 cookie/会话值。但我不知道怎么做。任何人都可以用例子来解释我。

我的应用程序依赖于包括身份验证在内的 Web Api 项目。我需要使用表单身份验证使 web api 应用程序安全。任何帮助都是非常可观的。谢谢

【问题讨论】:

    标签: asp.net-mvc authentication asp.net-web-api


    【解决方案1】:

    您无法通过使用 cookie 或会话来验证 web api。您需要访问令牌才能执行此操作。

    按照本教程实现http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

    【讨论】:

    • 感谢您的回复。我读了你分享的第一篇文章。我不想在 OAuth 的帮助下注册用户。我如何仅获取令牌并在我的 MVC 应用程序和 Web API 应用程序中用于安全 API 控制器操作方法调用。
    • 您可以实现自己的 OAuthAuthorizationServerProvider 来生成访问令牌并为用户的身份创建 ClaimsIdentity
    • 为什么不以普通的 MVC 方式(通过表单)进行身份验证,创建身份验证 cookie 和身份,然后在任何 ApiController ajax 方法中检查身份?如果它有问题 - 采取适当的措施。无需将事情过度复杂化...
    • 它是 Web Api 而不是 MVC。哈哈。
    猜你喜欢
    • 2018-10-10
    • 2012-10-22
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2020-08-24
    • 1970-01-01
    • 2011-12-22
    相关资源
    最近更新 更多