簡體   English   中英

ASP.NET WebApi FormsAuthentication 401(未經授權)問題

[英]ASP.NET WebApi FormsAuthentication 401 (Unauthorized) issue

我一直在學習授權在ASP.Net WebApi中的工作方式,並且在另一篇文章( ASP.NET Web API身份驗證 )中遇到了達林·迪米特洛夫(Darin Dimitrov)的回答,我需要一些幫助來理解為什么我會收到401。

按照Darin的代碼,我創建了一個WebApi項目並添加了以下控制器和模型:

AccountController.cs

using System.Web.Http;
using System.Web.Security;
using AuthTest.Models;

namespace AuthTest.Controllers
{
    public class AccountController : ApiController
    {
        public bool Post(LogOnModel model)
        {
            if (model.Username == "john" && model.Password == "secret")
            {
                FormsAuthentication.SetAuthCookie(model.Username, false);
                return true;
            }

            return false;
        }
    }
}

UsersController.cs

using System.Web.Http;

namespace AuthTest.Controllers
{
    [Authorize]
    public class UsersController : ApiController
    {
        public string Get()
        {
            return "This is top secret material that only authorized users can see";
        }
    }
}

LogOnModel.cs

namespace AuthTest.Models
{
    public class LogOnModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

我創建了一個帶有兩個按鈕和一個標簽的Web窗體應用程序,用於測試。

Default.aspx.cs

using System;
using System.Net.Http;
using System.Threading;

namespace AuthTestWebForms
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void ButtonAuthorizeClick(object sender, EventArgs e)
        {
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.PostAsJsonAsync(
                    "http://localhost/authtest/api/account",
                    new { username = "john", password = "secret" },
                    CancellationToken.None
                ).Result;
                response.EnsureSuccessStatusCode();

                bool success = response.Content.ReadAsAsync<bool>().Result;
                if (success)
                {
                    //LabelResponse.Text = @"Credentials provided";
                    var secret = httpClient.GetStringAsync("http://localhost/authtest/api/users");
                    LabelResponse.Text = secret.Result;
                }
                else
                {
                    LabelResponse.Text = @"Sorry, you provided the wrong credentials";
                }
            }
        }

        protected void ButtonTestAuthClick(object sender, EventArgs e)
        {
            using (var httpClient = new HttpClient())
            {
                var secret = httpClient.GetStringAsync("http://localhost/authtest/api/users");
                LabelResponse.Text = secret.Result;
            }
        }
    }
}

當我單擊按鈕並運行ButtonAuthorizeClick()時,它為Account觸發控制器,然后為Users觸發控制器,一切正常。

如果再單擊ButtonTestAuthClick(),則會收到401(未經授權)錯誤。

當我在Chrome或FireFox中尋找ASPXAUTH cookie時,沒有看到它,因此我不確定100%為什么ButtonAuthorizeClick()可以工作,以及我需要做什么來使ButtonTestAuthClick()起作用。

感謝您的幫助,任何人都可以拋棄我。

我遇到了類似的問題,雖然不是通過Web窗體客戶端頁面,而是通過JavaScript和AJAX調用。 原來我已將身份驗證模式留在web.config中的“無”位置。 顯然,為了使FormsAuthentication.SetAuthCookie()方法生效,您必須在此處打開Forms Authentication。

<authentication mode="Forms" />

一旦我糾正了這一疏忽,一切都會開始正常。 :-)

您正在調用帶有身份驗證的Web API。 為什么不通過ajax不對客戶端的用戶進行身份驗證?

這里的問題是每次您通過HttpClient向Web api發送請求時,它實際上是服務器處理的新Web請求。 所有cookie信息都不會保留在當前請求中。 為了支持這種情況,您需要自己處理cookie。

例如:如果響應中包含Cookie ASPXAUTH,則將其設置為ButtonAuthorizeClick方法中的asp.net標頭。 將cookie ASPXAUTH設置為HttpRequestMessage並由HttpClient發送。

Web API最近添加了對使用HttpServer來創建進程內服務器的支持,並且可以將請求直接發送到當前進程中的當前消息處理程序。 因此,您可以編寫如下代碼:

HttpClient c = new HttpClient(new HttpServer(GlobalConfiguration.DefaultHandler));
c.GetStringAsync("http://localhost/api/Values").Wait();

要將請求發送到進程內,以便在Web api操作中設置的cookie標頭仍將在當前請求的管道中。 簽入似乎不在RTM版本中。 您可以嘗試每晚進行構建http://aspnetwebstack.codeplex.com/discussions/353867

盡管已經晚了,但ButtonTestAuthClick中的客戶端不是瀏覽器。 這是httpClient對象。 因此,您需要以編程方式設置從其他按鈕生成的cookie。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM