Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code after openid connect sign-in in Asp.net Core

I am trying to figure out the best way to run some code once a user has authenticated themselves using OpenID Connect on a Dotnet Core MVC App. I don't want to hard code a redirect URL after sign-in because they still need to end up where they were trying to get to after authentication. I just need to run code eg. "check if its the first time sign-in and set a flag" or something similar.

I was using a middle-ware but since this gets called for every request its causing some problems.

Does anyone have any ideas on how to achieve this?

like image 556
Mitch Dart Avatar asked Jun 07 '17 11:06

Mitch Dart


People also ask

What is AddOpenIdConnect?

AddOpenIdConnect(AuthenticationBuilder) OpenID Connect is an identity layer on top of the OAuth 2.0 protocol. It allows clients to request and receive information about authenticated sessions and end-users.

What is UseOpenIdConnectAuthentication?

UseOpenIdConnectAuthentication is obsolete. Configure OpenIdConnect authentication with AddAuthentication(). AddOpenIdConnect in ConfigureServices. See https://go.microsoft.com/fwlink/?linkid=845470 for more details. UseOpenIdConnectAuthentication(IApplicationBuilder, OpenIdConnectOptions)

What is AddIdentityServerJwt?

The AddIdentityServerJwt method will configure the necessary pieces so that the IdentityServer application knows how to host the secure Web API and authentication service in the same web application. This step will be essential because the authentication server is usually a separate entity from the APIs it's securing.


1 Answers

I am using OpenIdConnect events to solve this problem.

.AddOpenIdConnect("oidc", options =>
{
   options.Events = new OpenIdConnectEvents
   {
       OnTokenValidated = async ctx =>
       {
           var userID = ctx.Principal.FindFirstValue("sub");

           var db = ctx.HttpContext.RequestServices.GetRequiredService<MyDb>();

           //Do things I need to do with the user here.

       }
   }
}
like image 118
Mitch Dart Avatar answered Oct 12 '22 16:10

Mitch Dart