Intercept asp.net core Authorize action to perform custom action upon successful authorization

亡梦爱人 提交于 2019-11-29 15:42:22

The OpenIDConnectOptions class has an Events property, that is intended for scenarios like this. This Events property (OpenIdConnectEvents) has an OnTokenValidated property (Func<TokenValidatedContext, Task>), which you can overwrite in order to be notified when a token is, well, validated. Here's some code:

options.Events.OnTokenValidated = ctx =>
{
    // Your code here.
    return Task.CompletedTask;
};

In the sample code, ctx is a TokenValidatedContext, which ultimately contains a Principal property (ClaimsPrincipal): You should be able to use this property to obtain the claims, etc, that you need using e.g. ctx.Principal.FindFirst(...).

As @Brad mentions in the comments, OnTokenValidated is called for each request and (based on your own comment), will not contain the UserInfo that you need. In order to get that, you can use OnUserInformationReceived, like so:

options.Events.OnUserInformationReceived = ctx =>
{
    // Here, ctx.User is a JObject that should include the UserInfo you need.
    return Task.CompletedTask;
};

ctx in this example is a UserInformationReceivedContext:It still includes the Principal property but also has a User property (JObject), as I called out in the code with a comment.

You should look at OpenIdConnectOptions.Events. I don't have an example to hand, but that's the place to hook into the OIDC middleware.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!