【发布时间】: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