Asp.net 如何提供用户身份?

Asp.net 如何提供用户身份?,asp.net,iis,owin,Asp.net,Iis,Owin,tl;dr:Owin与HttpApplication.AuthenticateRequest事件的等价物是什么 背景 在IIS上运行ASP.net站点时,全局对象在每个请求期间引发一个事件 各种http模块(如内置的FormsAuthentication)可以附加到事件。事件处理程序按注册顺序调用。设置HttpContext.Current.User的第一个处理程序是使用的身份验证 订阅此事件的模块的任务是将HttpContext.Current.User设置为某些主体: IIdentity i

tl;dr:Owin与HttpApplication.AuthenticateRequest事件的等价物是什么

背景 在IIS上运行ASP.net站点时,全局对象在每个请求期间引发一个事件

各种http模块(如内置的FormsAuthentication)可以附加到事件。事件处理程序按注册顺序调用。设置
HttpContext.Current.User
的第一个处理程序是使用的身份验证

订阅此事件的模块的任务是将
HttpContext.Current.User
设置为某些主体

IIdentity identity = new GenericIdentity("MBurns", "ContosoAuthentcation");
IPrincipal principal = new GenericPrincipal(identity, null);

HttpContext.Current.User = principal;
一旦分配了
HttpContext.Current.User
,ASP.net就会知道该用户已通过身份验证。(一旦用户通过身份验证,他们就不再是匿名的)

任何模块都可以做到这一点 任何人都可以使用
web.config
向ASP.net注册自己的
IHttpModule

web.config

<system.webServer>
   <modules runAllManagedModulesForAllRequests="true">
      <add name="MySuperCoolAuthenticationModule" type="ContosoAuthModule" />
   </modules>
</system.webServer>
然后,您可以执行验证用户所需的操作,如果他们是有效用户,请设置
HttpContext.Current.user

private void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
   var request = HttpContext.Current.Request;
   String username = SomeStuffToFigureOutWhoIsMakingTheRequest(request);

   if (String.IsNullOrWhiteSpace(username))
   {
      //I don't know who they are :(
      return;
   }

   //I know who they are, they are [username]!
   IIdentity identity = new GenericIdentity(username, "ContosoSuperDuperAuthentication");
   HttpContext.Current.User = new GenericPrincipal(identity, null);
}
这些都是HttpApplication MSDN记录了由HttpApplication引发的各种事件,以及它们的顺序:

()

  • 验证请求,该请求检查浏览器发送的信息,并确定其是否包含潜在的恶意标记。有关详细信息,请参阅和
  • 如果在Web.config文件的节中配置了任何URL,则执行URL映射
  • 提出该事件
  • 发起活动。
  • 提出该事件
  • 提出该事件
  • 提出该事件
  • 提出该事件
  • 当它是ASP.net和HttpApplication时,这一切都很棒。一切都很好理解,很容易解释(在上面的半个屏幕中),并且工作正常

    但是HttpApplication已经过时了

    Owin是新的热点 现在一切都应该准备好了HttpApplication位于
    System.Web
    中。人们希望与
    System.Web
    隔离。他们想让这名为“奥温”的人现在负责

    为了进一步实现该目标,它们(即任何新的ASP.net MCV、web表单或Signal网站)完全禁用ASP.net的身份验证系统:

    <system.web> 
       <authentication mode="None" />
    </system.web> 
    

    请查看此网站的博客文章。它解释了如何使用OWIN解决“此请求的授权已被拒绝”的问题

    JWTHandler类

    public static void OnAuthenticateRequest(IOwinContext context)
            {
                var requestHeader = context.Request.Headers.Get("Authorization");
                int userId = Convert.ToInt32(JwtDecoder.GetUserIdFromToken(requestHeader).ToString());
                var identity = new GenericIdentity(userId.ToString(), "StakersClubOwinAuthentication");
                //context.Authentication.User = new ClaimsPrincipal(identity);
    
                var token = requestHeader.StartsWith("Bearer ") ? requestHeader.Substring(7) : requestHeader;
                var secret = WebConfigurationManager.AppSettings.Get("jwtKey");
                Thread.CurrentPrincipal = ValidateToken(
                    token,
                    secret,
                    true
                    );
                context.Authentication.User = (ClaimsPrincipal) Thread.CurrentPrincipal;
                //if (HttpContext.Current != null)
                //{
                //    HttpContext.Current.User = Thread.CurrentPrincipal;
                //}
            }
    
    public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                var config = new HttpConfiguration();
    
                app.Use((context, next) =>
                {
                    JwtAuthHandler.OnAuthenticateRequest(context); //the new method
                    return next.Invoke();
                });
                app.UseStageMarker(PipelineStage.Authenticate);            
                WebApiConfig.Register(config);//Remove or comment the config.MessageHandlers.Add(new JwtAuthHandler()) section it would not be triggered on execution.
    
    
                app.UseWebApi(config);
            }
    
    
    
        }
    
    创业类

    public static void OnAuthenticateRequest(IOwinContext context)
            {
                var requestHeader = context.Request.Headers.Get("Authorization");
                int userId = Convert.ToInt32(JwtDecoder.GetUserIdFromToken(requestHeader).ToString());
                var identity = new GenericIdentity(userId.ToString(), "StakersClubOwinAuthentication");
                //context.Authentication.User = new ClaimsPrincipal(identity);
    
                var token = requestHeader.StartsWith("Bearer ") ? requestHeader.Substring(7) : requestHeader;
                var secret = WebConfigurationManager.AppSettings.Get("jwtKey");
                Thread.CurrentPrincipal = ValidateToken(
                    token,
                    secret,
                    true
                    );
                context.Authentication.User = (ClaimsPrincipal) Thread.CurrentPrincipal;
                //if (HttpContext.Current != null)
                //{
                //    HttpContext.Current.User = Thread.CurrentPrincipal;
                //}
            }
    
    public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                var config = new HttpConfiguration();
    
                app.Use((context, next) =>
                {
                    JwtAuthHandler.OnAuthenticateRequest(context); //the new method
                    return next.Invoke();
                });
                app.UseStageMarker(PipelineStage.Authenticate);            
                WebApiConfig.Register(config);//Remove or comment the config.MessageHandlers.Add(new JwtAuthHandler()) section it would not be triggered on execution.
    
    
                app.UseWebApi(config);
            }
    
    
    
        }
    

    你解决过这个问题吗?我对同样的事情很感兴趣。@deezg我从来没有这样做过。这没什么大不了的,因为我们都知道IIS和System.Web是行不通的。我刚刚注释掉了web.config中的
    authentication mode=“None”
    设置(并轻轻地拍了一下Owin的头:“那很好,亲爱的”):谢谢你的回复。我现在也差不多。你最近试过吗?这个应用程序似乎对我有用:在浏览器上显示“Hello world MBurns”(我将WriteAsync输出更改为使用HttpContext.Current.User.Identity.Name)。