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

时间:2015-08-16 19:49:47

标签: 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;

这里我得到了相同的身份:AuthenticationType = null; IsAuthenticated = FALSE; NAME = NULL;权利要求:空

var token = Request.Headers.Authorization;

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

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

以下是我的代码的一部分: 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);
    }
}

控制器方法:

#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

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 }
        );
    }
}

启动:

[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);

    }

}

2 个答案:

答案 0 :(得分:12)

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

问题出在初创公司。我只需在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);

    }

}

答案 1 :(得分:0)

我的猜测是,令牌未从客户端正确发送。您是否发送了授权令牌,前面带有“Bearer”字样?

授权标题应该如下所示 -

Authorization:Bearer reNjoIUZBJHCMigQJHzCgMMVUyu4vg

查看Chrome开发人员工具网络标签,查看发送的内容。