微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 Microsoft.Identity.Web 登录/注销中捕获事件

如何解决从 Microsoft.Identity.Web 登录/注销中捕获事件

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

请告诉我是否存在我尚未找到的文档和/或如何编写自定义注入来记录这些事件。

谢谢!

解决方法

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

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

我创建了这个中间件类

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();
            });
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。