Authorize Attribute Not working in Web API 2.2 using OAuth2

好久不见. 提交于 2020-01-17 05:08:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!