asp.net-mvc - 如何从 Owin Middleware 正确登录用户

标签 asp.net-mvc asp.net-web-api asp.net-identity owin

我正在制作自己的系统来在某些情况下验证 jwt token 。

当我正确验证 token 后,我已经

var userIdentity = await user.CreateIdentityAsync(DefaultAuthenticationTypes.ExternalBearer);
owinContext.Authentication.User = new System.Security.Claims.ClaimsPrincipal(userIdentity);
owinContext.Authentication.SignIn(userIdentity);
System.Web.HttpContext.Current.User = owinContext.Authentication.User;
await next()

但这似乎并不能解决身份验证问题,我相信,在 Asp.Net Mvc 级别仍然失败。因为我知道它使用 HttpContext 我尝试在调用 next()

之前添加它
HttpContext.Current.User = new GenericPrincipal(userIdentity, new string[0]);

这让我走得更远,但我似乎仍然收到一个授权错误,它似乎(通过搜索我收到的消息的来源和 where its used )来自 Web Api [Authorize] 属性。

在追踪 .net 源代码方面我遇到了困难。我收到此消息的唯一方法是 if IsAuthorized返回假。但是没有指定角色或用户(只是简单的 [Authorize]),在前往 next() 之前,我可以停止调试器并检查是否存在用户身份,是的,它IsAuthorized

我已经重写了 AuthorizeAttribute 以便放置断点,并且可以看到,在调用它时,我的 actionContext 与一个完全不同的身份关联IsAuthorized == false。这又让我怀疑我是否登录了错误的用户身份

那么...我这样做正确吗?我应该做什么?

最佳答案

我从来不明白为什么,但就我而言,我需要在登录后验证票证:

var userIdentity = await user.CreateIdentityAsync(DefaultAuthenticationTypes.ExternalBearer);
ctx.Authentication.SignIn(userIdentity);
AuthenticationTicket ticket = new AuthenticationTicket(userIdentity, null);
ctx.Validated(ticket);

编辑

我并不真正处于同一环境中。就我而言,我有一个继承 Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationProvider 的自定义身份验证提供程序:

public class CustomBearerAuthenticationProvider:OAuthBearerAuthenticationProvider
{
    public CustomBearerAuthenticationProvider() : base()
    {
        this.OnValidateIdentity = (context) => Task.Run(() =>
        {
            var identity = this.CreateApplicationIdentity(user);
            context.OwinContext.Authentication.SignIn(identity);
            AuthenticationTicket ticket = new AuthenticationTicket(identity, null);
            context.Validated(ticket);
        });
    }
}

context 的类型为:Microsoft.Owin.Security.OAuth.OAuthValidateIdentityContext

关于asp.net-mvc - 如何从 Owin Middleware 正确登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54566167/

相关文章:

c# - 实现 SimpleMembership 时无法找到 .net 数据提供程序异常

asp.net-mvc - Windows Azure,OpenID 后退按钮错误

c# - 如何在WebAPI Controller 中接收动态数据

c# - Web API 不会将 bool 返回类型序列化为 json boolean 值

c# - .NET 标识 : Generate token without explicit username/password

c# - MVcHtmlString 中的堆栈溢出异常

javascript - 如何使用 mvc 将 anchor 标记类 Id 传递给函数变量?

c# - asp.net core webapi frombody参数大小限制

c# - 如何在 ASP.NET MVC 上获取 session IsPersistent?

C# Azure 身份验证和身份