【问题标题】:Why is IIdentity getting reset / replaced in ASP.NET Web API?为什么 IIdentity 在 ASP.NET Web API 中被重置/替换?
【发布时间】:2016-03-09 17:09:30
【问题描述】:

在 ASP.Net Web API 方法上使用 [Authorize] 属性会导致“401 Unauthorized”响应。

我有一个处理 context.AuthenticateRequest 事件的 Http 模块,在该事件中我检查请求的授权标头(Basic 授权),如果有效,则将 System.Threading.Thread.CurrentPrincipal 设置为包含一个新的 GenericPrincipal新的GenericIdentity 基于授权标头中的信息。我还将HttpContext.Current.User 设置为GenericPrincipal 的同一实例。

此时,IIdentity 的IsAuthenticated 属性为真。但是,在调用控制器中的操作方法时,System.Threading.Thread.CurrentPrincipal 已设置为包含System.Security.Claims.ClaimsIdentity 的System.Security.Claims.ClaimsPrincipal,其中IsAuthenticated = false。

所以...在我设置 CurrentPrincipal 的点和到达操作方法时的管道中某处,CurrentPrincipal 和身份正在被替换。

API 访问 ASP.Net Identity 用户的一些方法(对于相关网站,API 本身不使用 ASP.Net Identity 进行身份验证/授权),所以 API 项目设置了所有相关的 ASP .Net Identity NuGet 包等。

我在其他没有所有 ASP.Net Identity NuGet 包等的 API 项目中使用了相同的 Http 模块,它的工作原理就像一个冠军。

我怀疑 ASP.Net 身份配置导致我的 Basic 身份验证 System.Security.Claims.ClaimsPrincipal 被替换。

任何帮助将不胜感激!

这是我的代码:
Http 模块 - 在这个方法的最后,System.Threading.Thread.CurrentPrincipal 和 HttpContext.Current.User 设置正确。

public class FsApiHttpAuthentication : IHttpModule, IDisposable {
    public void Init( HttpApplication context ) {
        context.AuthenticateRequest += AuthenticateRequests;
        context.EndRequest += TriggerCredentials;
    }

    private static void AuthenticateRequests( object sender, EventArgs e ) {
        string authHeader = HttpContext.Current.Request.Headers["Authorization"];
        if ( authHeader != null ) {
            System.Net.Http.Headers.AuthenticationHeaderValue authHeaderVal = System.Net.Http.Headers.AuthenticationHeaderValue.Parse(authHeader);
            if ( authHeaderVal.Parameter != null ) {
                byte[] unencoded = Convert.FromBase64String(authHeaderVal.Parameter);
                string userpw = System.Text.Encoding.GetEncoding("iso-8859-1").GetString(unencoded);
                string[] creds = userpw.Split(':');
                CredentialCache.Credential cred = CredentialCache.GetCredential(creds[0], creds[1]);
                if ( cred != null ) {
                    System.Security.Principal.GenericIdentity identity = new System.Security.Principal.GenericIdentity
                    (cred.Username);System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.GenericPrincipal(identity, roles);
                    if ( string.IsNullOrWhiteSpace(cred.RolesList) ) {
                         System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.GenericPrincipal(identity, null);
                    } else {
                        System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.GenericPrincipal(identity, cred.RolesList.Split(','));
                    }

                    HttpContext.Current.User = System.Threading.Thread.CurrentPrincipal;
                }
            }
        }
    }

Api 控制器 - 当达到此控制器中的 Post 操作时,System.Threading.Thread.CurrentPrincipal 和 HttpContext.Current.User 已设置为包含 System.Security.Claims.ClaimsIdentity 和 IsAuthenticated = 的 System.Security.Claims.ClaimsPrincipal错误的。

public class ConsumerAccountController : ApiController {
    private ApplicationUserManager _userManager;
    private ApplicationUserManager UserManager {
        get {
            return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
        set {
            _userManager = value;
            }
    }

    public async System.Threading.Tasks.Task<IHttpActionResult> Post( API.FinancialSamaritan.com.ViewModels.UserCredentials creds ) {
        API.FinancialSamaritan.com.ViewModels.CreateUserResult cccur = null;
        try {
            string username = creds.Username;
            string password = creds.Password;

            var user = new API.FinancialSamaritan.com.Models.ApplicationUser {
                UserName = username,
                Email = username,
                SecurityQuestion = creds.SecurityQuestion,
                SecurityAnswer = UserManager.PasswordHasher.HashPassword(creds.SecurityAnswer),
                IsPasswordChangeRequired = true,
                EmailConfirmed = true
            };
            IdentityResult userResult = await UserManager.CreateAsync(user, password);
            ...

【问题讨论】:

  • 显示您的代码,并确保您的命名空间是任何过滤器应有的名称。当我想进入 Web 时,我一直被 MVC 命名空间所困扰。
  • 谢谢,@Ron-Brogan。我添加了我的代码。
  • @RonBrogan,你是对的!实际上,它使用了来自MVC 命名空间的[Authorize] 属性,而不是System.Web 命名空间。如果您想使用此信息创建“答案”,我会将其标记为已接受的答案。

标签: asp.net .net asp.net-web-api authorization basic-authentication


【解决方案1】:

[Authorize] 属性派生自 System.Web.Http.AuthorizeAttribute 而不是 System.Web.Mvc.AuthorizeAttribute。我必须完全限定属性的命名空间,以便使用 [Authorize] 的 MVC 版本。感谢@RonBrogan 为我指明了正确的方向!

【讨论】:

  • 您在 Ron 说您正在获得 MVC 并想要 Web 但您的回答说您正在获得 Web 并想要 Mvc 之后的评论。只是想知道它是哪个?我在一条切线相关的船上。我有一个从 Web 派生的 AuthorizeAttribute,它在我的 Web Api 控制器上工作了很长时间。我添加了 Odata 库以将一些 odata apis 放在另一个目录中,突然我遇到了“CurrentPrincipal 在 [Authorize] 和方法调用之间交换”问题
  • AuthorizeAttributes 的签名在 Web 和 MVC 之间有很大的不同;很难看到如果不重新工具,一个人怎么会在错误的命名空间中,至少对于你从 Nuget 获得的 Odata 的东西
猜你喜欢
  • 1970-01-01
  • 2015-10-22
  • 2015-10-05
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 2018-01-27
  • 2012-04-03
相关资源
最近更新 更多