简体   繁体   English

ASP.Net Core 2 如何在身份验证后触发/调用代码

[英]ASP.Net Core 2 how to trigger/call code after authentication

How can I trigger some code right after authentication?如何在身份验证后立即触发某些代码? Let's say I want to give my application a single session constraint per user, for example.例如,假设我想为我的应用程序为每个用户提供一个会话约束。 How can I implement it in ASP.Net Core 2.0?如何在 ASP.Net Core 2.0 中实现它?

Update:更新:

Clarification, I want to trigger code right after a user is considered authenticated (after .net authentication middleware have validated the user is who claims to be).澄清一下,我想在用户被认为通过身份验证后立即触发代码(在 .net 身份验证中间件验证用户是谁之后)。 I have not mentioned Middleware before because there might be an easier way, like an event, to trigger some code.我之前没有提到中间件,因为可能有更简单的方法,比如事件,来触发一些代码。 Maybe the proper question would be if is there such event/way, or if I should manage it through a custom Middleware attached right after Authentication?也许正确的问题是是否有这样的事件/方式,或者我是否应该通过身份验证后立即附加的自定义中间件来管理它?

The simplest scenario, is calling the method you want in any action in MVC controller.最简单的场景是在 MVC 控制器中的任何操作中调用您想要的方法。 Actions are always called after authentication (I think this is not what you need, but the information your provided are very poor, as you did not mentioned exactly what do you mean by right after authentication ).操作总是在身份验证后调用(我认为这不是您需要的,但是您提供的信息非常差,因为您没有提到身份验证后的确切含义)。

The other possiblity ( which is probably what you want ), is to create a middleware , and add it to the pipeline exactly after authentication middleware.另一种可能性(这可能是您想要的)是创建一个中间件,并在身份验证中间件之后将其添加到管道中。 When you have your middleware in the pipeline, you can write to do what ever you want.当您的中间件在管道中时,您可以编写以执行您想要的任何操作。

Middleware writing is well documented here:中间件编写在这里有很好的记录:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM