Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

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

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 now want to start writing user claims to the web app db every time a user logs in. To do this I need to have some code that runs on the web app every time a user is successfully logged in / authorised.

I have been given a clue that it involves adding custom middleware.

My Startup ConfigureServices code is currently as follows:

public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;
        Env = env;
    }

    public IHostingEnvironment Env { get; }
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddMvc();

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.Cookie.HttpOnly = true;
        });

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                options.SignInScheme = "Cookies";
                options.Authority = Configuration["auth:oidc:authority"];                    

                options.RequireHttpsMetadata = !Env.IsDevelopment();
                options.ClientId = Configuration["auth:oidc:clientid"];
                options.ClientSecret = Configuration["auth:oidc:clientsecret"];
                options.ResponseType = "code id_token"; 

                options.Scope.Add(Configuration["auth:oidc:clientid"]);
                options.Scope.Add("offline_access");

                options.GetClaimsFromUserInfoEndpoint = true;
                options.SaveTokens = true;

            });

    }

... []

So my question: what code do I need to add, and where, in order to call a method that will contain my custom action?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...