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

后端 未结 2 1879
盖世英雄少女心
盖世英雄少女心 2020-12-19 11:28

I have an [Authorize] attribute on my web app controller so any endpoints hit ensure user is re-directed to login on OAuth server first (if not already logged in.)

I

相关标签:
2条回答
  • 2020-12-19 12:21

    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.

    0 讨论(0)
  • 2020-12-19 12:23

    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.

    0 讨论(0)
提交回复
热议问题