软件编程
位置:首页>> 软件编程>> C#编程>> 详解.NET 6如何实现获取当前登录用户信息

详解.NET 6如何实现获取当前登录用户信息

作者:CODE4NOTHING  发布时间:2022-01-29 12:51:15 

标签:.NET6,用户,信息

需求

在前面的文章里使用.NET 6开发TodoList应用之领域实体创建原理和思路,我们留了一个坑还没有填上,就是在数据库保存的时候,CreateUser和ModifiedUser我们当时填的都是Anonymous,完成认证的功能后,现在我们需要实现在保存数据库的时候填入当前登陆进行操作的用户名。

目标

实现当前登陆用户信息获取。

原理和思路

原理很简单,在认证时拿到的Token里,payload中是包含登陆User的部分信息的,作为演示,我们需要想办法获取到用户名信息,并在保存数据时填入相应字段。为了获取Token中包含的用户信息,需要用到HttpContextAccessor对象。很显然,需要一个新的接口和实现。

实现

创建当前用户获取接口

Application/Common/Interfaces中添加一个新的接口:

ICurrentUserService.cs

namespace TodoList.Application.Common.Interfaces;

public interface ICurrentUserService
{
   string? UserName { get; }
}

这里我们取的是UserName,是因为在返回的Token中包含UserName的信息,如果需要使用UserId或其他信息,需要在GetClaims中添加:

// 演示了返回用户名和Role两个claims
var claims = new List<Claim>
{
   // Claims中包含UserName信息
   new(ClaimTypes.Name, User!.UserName),
   new(JwtRegisteredClaimNames.Iss, _jwtConfiguration.ValidIssuer ?? "TodoListApi"),
   new(JwtRegisteredClaimNames.Aud, _jwtConfiguration.ValidAudience ?? "http://localhost:5050")
};

实现接口功能

Api/Services中添加类实现接口:

CurrentUserService.cs

using System.Security.Claims;
using TodoList.Application.Common.Interfaces;

namespace TodoList.Api.Services;

public class CurrentUserService : ICurrentUserService
{
   private readonly IHttpContextAccessor _httpContextAccessor;

public CurrentUserService(IHttpContextAccessor httpContextAccessor)
   {
       _httpContextAccessor = httpContextAccessor;
   }

// 通过注入的IHttpContextAccessor获取`HttpContext.User(ClaimsPrinciple)`中对应的Claims信息
   public string? UserName  => _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.Name);
}

并在Program中添加依赖注入:

Program.cs

builder.Services.AddSingleton<ICurrentUserService, CurrentUserService>();

使用功能

接下来我们去修改DbContext,需要先在构造函数中注入:

TodoListDbContext.cs

private readonly ICurrentUserService _currentUserService;
public TodoListDbContext(
   DbContextOptions<TodoListDbContext> options,
   IDomainEventService domainEventService,
   ICurrentUserService currentUserService) : base(options)
{
   _domainEventService = domainEventService;
   _currentUserService = currentUserService;
}

SaveChangesAsync方法中修改:

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new())
{
   foreach (var entry in ChangeTracker.Entries<AuditableEntity>())
   {
       switch (entry.State)
       {
           case EntityState.Added:
               entry.Entity.CreatedBy = _currentUserService.UserName;
               entry.Entity.Created = DateTime.UtcNow;
               break;
           case EntityState.Modified:
               entry.Entity.LastModifiedBy = _currentUserService.UserName;
               entry.Entity.LastModified = DateTime.UtcNow;
               break;
       }
   }
// 省略其他...
}

验证

启动Api项目,首先获取Token,再用获取到的Token去创建一个新的TodoList:

详解.NET 6如何实现获取当前登录用户信息

可以看到新创建的TodoList的用户信息已经获取到了,为了确保数据存储到数据库中,我们去数据库看一下:

详解.NET 6如何实现获取当前登录用户信息

来源:https://www.cnblogs.com/code4nothing/p/15816590.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com