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?
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.
来源:https://stackoverflow.com/questions/49690300/intercept-asp-net-core-authorize-action-to-perform-custom-action-upon-successful