1

I was able to get this example working https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect-aspnetcore/

My question is how to do something additional after authentication. For example, on a typical Login page, in the POST after validating, I could set a log record for the user or set additional cookies.

With Azure AD integration I'm not sure where to put such code that should be executed only once the user has been authenticated. The reply URL (call back path) does not work for this purpose (I tried putting my custom page here and it really didn't get executed. Apparently the middle-ware creates a special route for that end point so that it can process the login token data)

Any help is appreciated!

Nelson Rodriguez
  • 492
  • 3
  • 12

1 Answers1

1

There are some OpenIdConnectEvents which could be used to enable developer control over the authentication process.

For example , OnAuthorizationCodeReceived is invoked after security token validation if an authorization code is present in the protocol message. The event could be used to get access token for accessing API using authorization Code using ADAL/MSAL in Code/Hybrid Flow :

    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
    {
        // Acquire a Token for the Graph API and cache it using ADAL. In the TodoListController, we'll use the cache to acquire a token for the Todo List API
        string userObjectId = (context.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
        var authContext = new AuthenticationContext(context.Options.Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));
        var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);

        var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code,
            new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, context.Options.Resource);

        // Notify the OIDC middleware that we already took care of code redemption.
        context.HandleCodeRedemption(authResult.AccessToken, context.ProtocolMessage.IdToken);
    }

Code sample link : Calling a web API in an ASP.NET Core web application using Azure AD.

OnTokenValidated could be used to add custom claims to a user during authentication. Please check above document to get more events .

Lukas
  • 1,699
  • 1
  • 16
  • 49
Nan Yu
  • 26,101
  • 9
  • 68
  • 148
  • Thank you! I got to investigate this and in fact I found an answer with more details which solved exactly what my issue was: https://stackoverflow.com/a/54599668/1037940 – Nelson Rodriguez Apr 15 '19 at 14:47