问题
I'm placing an [Authorize(Users = "user@sample.com")]
attribute at the top of my Controller:
[Authorize(Users = @"user@sample.com")]
public class PostsController : ApiController
{
... methods...
}
The user's usernames are the email address. When I sign in with user@sample.com
I still get a 401 Unauthorized this controller's methods.
I've also notice that, even after the user signs in both System.Web.HttpContext.Current.User.Identity.Name
and System.Security.Claims.ClaimsPrincipal.Current.Identity.Name
are null
.
These are a few related classes:
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
public string Hometown { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
// Add custom user claims here
return userIdentity;
}
}
ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MyProjectEntitiesIdentity", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
The issue happens on my local dev instance as well as on the hosted site.
I know this is very vague, I just don't know what other issues may be relevant here. So, please ask for more information and I will update the post.
来源:https://stackoverflow.com/questions/35296699/authorize-attribute-not-working-in-web-api-2-2-using-oauth2