首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Microsoft.Identity.Web登录/注销捕获事件

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

Stack Overflow用户
提问于 2021-05-01 00:33:31
回答 1查看 91关注 0票数 0

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

请让我知道是否存在我还没有找到的文档和/或如何编写自定义注入来记录这些事件。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-06 01:07:07

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

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

我创建了这个中间件类

代码语言:javascript
复制
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中:

代码语言:javascript
复制
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();
            });
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67337434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档