gpt4 book ai didi

asp.net - 如何赋予 Owin 用户身份?

转载 作者:行者123 更新时间:2023-12-04 06:37:42 25 4
gpt4 key购买 nike

tl;博士 : 的 Owin 等价物是什么? HttpApplication.AuthenticateRequest 事件?

背景

在 IIS 上运行 ASP.net 站点时,全局 System.Web.HttpApplication对象引发 AuthenticateRequest每个请求期间的事件。

各种 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自己注册 IHttpModule使用 ASP.net:

web.config
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="MySuperCoolAuthenticationModule" type="ContosoAuthModule" />
</modules>
</system.webServer>

该模块很容易编写。你实现了孤独的 Init IHttpModule 的方法界面。对我们来说,我们将自己添加为 验证请求 事件处理程序:
public class ContosoAuthModule : IHttpModule
{
public void Init(HttpApplication httpApplication)
{
// Register event handlers
httpApplication.AuthenticateRequest += OnApplicationAuthenticateRequest;
}
}

然后您可以执行验证用户所需的操作,如果他们是有效用户,请设置 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 ,以及按什么顺序:

ASP.NET Application Life Cycle Overview for IIS 7.0 (archive.is)

  1. Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequesta and Script Exploits Overviewa.
  2. Perform URL mapping, if any URLs have been configured in the UrlMappingsSectiona section of the Web.config file.
  3. Raise the BeginRequest event.
  4. Raise the AuthenticateRequesta event.
  5. Raise the PostAuthenticateRequest event.
  6. Raise the AuthorizeRequest event.
  7. Raise the PostAuthorizeRequest event.
  8. Raise the ResolveRequestCache event.


当它是 ASP.net 和 时,这一切都很棒HttpApplication .一切都很好理解,很容易解释(在上面的半屏中),并且有效。

但是 HttpApplication 又旧又破。

欧文是新的热点

现在一切都应该是欧文。 HttpApplication 住在 System.Web .人们希望与 System.Web 隔离开来.他们想要这个叫做 的东西欧文 现在负责。

为了进一步实现这一目标,他们(即任何新的 ASP.net MCV、网络表单或 SignalR 网站)完全禁用了 ASP.net 的身份验证系统:
<system.web> 
<authentication mode="None" />
</system.web>

所以没有了 HttpApplication.AuthenticateRequest 事件。 :(

什么是 Owin 等价物?

的 Owin 等价物是多少? HttpApplication.AuthenticateRequest ?

可以肯定地说,无论从哪里调用我的代码,我的工作仍然是设置 HttpContext.Current.User到一个身份。

是否可以肯定地说,无论我的代码在哪里调用表单,我的工作仍然是设置 HttpContext.Current.User一个身份?

的 Owin 等价物是多少? HttpApplication.AuthenticateRequest ?

尝试无效

它没有被称为:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using System.Web;
using System.IO;
using Microsoft.Owin.Extensions;
using System.Security.Claims;
using System.Security.Principal;

[assembly: OwinStartup("AnyStringAsLongAsItsNotBlank", typeof(BasicAuthOwin))]
public class BasicAuthOwin
{
public void Configuration(IAppBuilder app)
{
app.Use((context, next) =>
{
System.Diagnostics.Trace.WriteLine("They did their best, shoddily-iddly-iddly-diddly");
OnAuthenticateRequest(context);
return next.Invoke();
});
app.UseStageMarker(PipelineStage.Authenticate);

app.Run(context =>
{
return context.Response.WriteAsync("Hello world");
});
}

private void OnAuthenticateRequest(IOwinContext context)
{
var request = context.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, "ContosoSuperDuperOwinAuthentication");
context.Authentication.User = new ClaimsPrincipal(identity);
}

private string SomeStuffToFigureOutWhoIsMakingTheRequest(IOwinRequest request)
{
//if ((System.Diagnostics.Stopwatch.GetTimestamp % 3) == 0)
// return "";

return "MBurns";
}
}

最佳答案

查看此网站上的博客文章 Jwt Authentication in ASP.NET WEB API AND MVC .它解释了如何使用 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);
}



}

关于asp.net - 如何赋予 Owin 用户身份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37304395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com