Hi. I have an ASP .Net Core 1.1 MVC web app, with a Web API backend. I am using Auth0 for the authentication. When the user navigates to the web app, the Index page loads, and upon seeing that the user is not logged in, it redirects him to the Auth0 login page. After a successful login, he is redirected back to the Index page. I would like to insert one extra step in there. After the user successfully logs in, a controller method should fire, which calls upon a Web API action to check if the user is valid and hasn't been blocked, and which also logs the user login. If the Web API replies that the user is OK (and logs the login event to the DB) the web app should then redirect the user to the Index page. Otherwise it should redirect him to an "access denied" type page.
In my Configure() method in Startup, I have this:
{ AutomaticAuthenticate = true, AutomaticChallenge = true, Events = new CookieAuthenticationEvents() { OnRedirectToLogin = ctx => { // if it is an ajax / api request, don't redirect to login page. if (!(IsAjaxRequest(ctx.Request) || IsApiRequest(ctx.Request))) { ctx.Response.Redirect(ctx.RedirectUri); return Task.CompletedTask; } ctx.Response.StatusCode = StatusCodes.Status401Unauthorized; return ctx.Response.WriteAsync("Unauthorized"); } } }); // Add the OIDC middleware var options = new OpenIdConnectOptions("Auth0") { // Set the authority to your Auth0 domain Authority = $"https://{auth0Settings.Value.Domain}", // Configure the Auth0 Client ID and Client Secret ClientId = auth0Settings.Value.ClientId, ClientSecret = auth0Settings.Value.ClientSecret, // Do not automatically authenticate and challenge AutomaticAuthenticate = false, AutomaticChallenge = false, // Set response type to code ResponseType = OpenIdConnectResponseType.Code, // Set the callback path, so Auth0 will call back to http://localhost:5000/signin-auth0 // Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard CallbackPath = new PathString("/signin-auth0"), // Configure the Claims Issuer to be Auth0 ClaimsIssuer = "Auth0", // The UserInfo endpoint does not really return any extra claims which were not returned in the original auth response, so // we can save ourselves from making an extra request GetClaimsFromUserInfoEndpoint = false, // Saves tokens to the AuthenticationProperties SaveTokens = true, Events = new OpenIdConnectEvents { OnTicketReceived = context => { // Get the ClaimsIdentity var identity = context.Principal.Identity as ClaimsIdentity; if (identity != null) { // Add the Name ClaimType. This is required if we want User.Identity.Name to actually return something! if (!context.Principal.HasClaim(c => c.Type == ClaimTypes.Name) && identity.HasClaim(c => c.Type == "name")) identity.AddClaim(new Claim(ClaimTypes.Name, identity.FindFirst("name").Value)); // Check if token names are stored in Properties if (context.Properties.Items.ContainsKey(".TokenNames")) { // Token names a semicolon separated string[] tokenNames = context.Properties.Items[".TokenNames"].Split(';'); // Add each token value as Claim foreach (var tokenName in tokenNames) { // Tokens are stored in a Dictionary with the Key ".Token.<token name>" string tokenValue = context.Properties.Items[$".Token.{tokenName}"]; identity.AddClaim(new Claim(tokenName, tokenValue)); } } } return Task.CompletedTask; }, OnRedirectToIdentityProvider = context => { context.ProtocolMessage.Parameters.Add("audience", auth0Settings.Value.ApiIdentifier); return Task.CompletedTask; }, //handle the logout redirection OnRedirectToIdentityProviderForSignOut = (context) => { var logoutUri = $"https://{auth0Settings.Value.Domain}/v2/logout?client_id={auth0Settings.Value.ClientId}"; var postLogoutUri = context.Properties.RedirectUri; if (!string.IsNullOrEmpty(postLogoutUri)) { if (postLogoutUri.StartsWith("/")) { // transform to absolute var request = context.Request; postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; } logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; } context.Response.Redirect(logoutUri); context.HandleResponse(); return Task.CompletedTask; } }, };
Sorry, I know it's a lot of code... Would I need to set up the redirect there? I'm (probably erroneously) looking for a "logged in" event that is triggered after a successful login, in which I could then call the aforementioned Web API action to validate the
user and log the login?