从 Microsoft.Identity.Web Login/Logout 捕获事件

Capture Events From Microsoft.Identity.Web Login/Logout

我正在使用 Microsoft 的 Authentication/Authorization 平台来允许用户从 Azure AD 登录。我想将这些事件记录到数据库中。问题是,由于这种类型的身份验证利用了中间件,我不确定如何注入代码来触发日志事件。

如果存在我尚未找到的文档,请告诉我and/or如何编写自定义注入来记录这些事件。

谢谢!

我解决了我自己的问题。对于将来对其他任何人的任何潜在用处,我将在下面添加我所做的..

我根据这个文档设置了我的数据库:https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-5.0&tabs=visual-studio

我创建了这个中间件Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Identity.Web;
using Application.Models;
using Application.Data;

namespace Application.Middleware
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class EventLogCaptureMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly EventLogContext _context;

        public EventLogCaptureMiddleware(RequestDelegate next, EventLogContext context)
        {
            _next = next;
            _context = context;
        }

        public Task Invoke(HttpContext httpContext)
        {
            var eventLogModel = new EventLogViewModel
            {
                Timestamp = DateTime.Now,
                Type = "TEST",
                Method = httpContext.Request.Method,
                Upn = httpContext.User.Identity.Name,
                Resource = $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.Path}"
            };
            _context.Add(eventLogModel);
            var tasks = new Task[] { _context.SaveChangesAsync() };

            Task.WaitAll(tasks);

            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class EventLogCaptureMiddlewareExtensions
    {
        public static IApplicationBuilder UseEventLogCaptureMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<EventLogCaptureMiddleware>();
        }
    }
}

并像这样注入 Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //Production Exception Handler ex: API connection failed will trigger exception routed to /Home/Error
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //Handles User Error: 401, 403, 404, etc. Errors caught must land Application side. Errors occured in API with return 500 and be routed via Exception Handler
            app.UseStatusCodePagesWithReExecute("/Home/Error", "?status={0}");

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseRouting();

            //Must include Authentication/Authorization under routing
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEventLogCaptureMiddleware();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }