即使发送令牌,ASP.NET Identity也为null

And*_*Gyr 5 c# asp.net authentication asp.net-identity

对于我的论文项目,我必须在我的ASP.NET解决方案中实现基于令牌的(承载)身份验证.我像Taiseer Jouseh(http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity)那样实现了它.

基本部分工作正常.我有一个移动客户端,我可以在其上注册一个新用户.然后我可以登录并接收令牌.当我发出请求时,令牌将在请求标头中发送.一切正常.我的问题是,如果我调用[授权]方法,即使我发送令牌,我也会收到401 Unauthorized错误.所以我删除了[Authorize] Annotation来测试一些东西:

var z = User.Identity;
var t = Thread.CurrentPrincipal.Identity;
var y = HttpContext.Current.User.Identity;
var x = Request.GetOwinContext().Authentication.User.Identity;
Run Code Online (Sandbox Code Playgroud)

在这里我得到了相同的身份:AuthenticationType = null; IsAuthenticated = FALSE; NAME = NULL; 声明:空

var token = Request.Headers.Authorization;
Run Code Online (Sandbox Code Playgroud)

在这里,我得到了正确的令牌.因此令牌由请求发送.

我希望你能帮助我.我有令牌但没有身份.

以下是我的代码的一部分:OAuthServiceProvider:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{

    public async override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    // POST /token
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var userManager = DependencyResolver.Current.GetService<UserManager<IdentityUser, int>>();

        IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        var identity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));
        context.Validated(identity);
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器方法:

#region GET /user/:id
[HttpGet]
[Route("{id:int:min(1)}")]
[ResponseType(typeof(UserEditDto))]
public async Task<IHttpActionResult> GetUser(int id)
{
    try
    {
        // tests
        var z = User.Identity;
        var t = Thread.CurrentPrincipal.Identity;
        var y = HttpContext.Current.User.Identity;
        var x = Request.GetOwinContext().Authentication.User.Identity;
        var token = Request.Headers.Authorization;

        User user = await _userManager.FindByIdAsync(id);
        if (user == null)
        {
            return NotFound();
        }

        Mapper.CreateMap<User, UserEditDto>();
        return Ok(Mapper.Map<UserEditDto>(user));
    }
    catch (Exception exception)
    {
        throw;
    }

}
#endregion
Run Code Online (Sandbox Code Playgroud)

WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter("Bearer"));

        config.MapHttpAttributeRoutes();

        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);

        config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{id}",
             defaults: new { id = RouteParameter.Optional }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

启动:

[assembly: OwinStartup(typeof(Startup))]
public class Startup
{

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        var container = new UnityContainer();
        UnityConfig.RegisterComponents(container);
        config.DependencyResolver = new UnityDependencyResolver(container);
        //config.DependencyResolver = new UnityHierarchicalDependencyResolver(container);
        WebApiConfig.Register(config);
        app.UseWebApi(config);
        ConfigureOAuth(app);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

        // Token Generation
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        app.UseOAuthAuthorizationServer(OAuthServerOptions);

    }

}
Run Code Online (Sandbox Code Playgroud)

And*_*Gyr 13

最后我发现了问题.这很简单,我无法相信我花了一个多星期来解决这个问题.

问题出在初创公司.我ConfigureOAuth(app);以前只需打电话app.UseWebApi(config);

所以正确的Startup看起来像

[assembly: OwinStartup(typeof(Startup))]
public class Startup
{

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        var container = new UnityContainer();
        UnityConfig.RegisterComponents(container);
        config.DependencyResolver = new UnityDependencyResolver(container);
        //config.DependencyResolver = new UnityHierarchicalDependencyResolver(container);
        WebApiConfig.Register(config);
        ConfigureOAuth(app);
        app.UseWebApi(config);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

        // Token Generation
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        app.UseOAuthAuthorizationServer(OAuthServerOptions);

    }

}
Run Code Online (Sandbox Code Playgroud)