开源DDD设计模式框架YMNNetCoreFrameWork第四篇-增加YMNSession,增加异常处理,增加策略授权

1、增加YMNSession,可以获取当前登录的用户信息

2、增加异常处理,不要使用过滤器,过滤器只能获取到mvc异常

3、增加策略授权,策略授权支持用户角色、用户名授权,初步实现

 代码地址:https://github.com/topgunymn/YMNNetCoreFrameWork

获取当前登录用户信息

复制代码
 [HttpPost("Login")]
        public async Task<object> Login(string name, string password) {
            YMNSession.Configure(_httpContextAccessor);
            var user = await _userManager.FindByNameAsync(name);
            var result = await _signInManager.PasswordSignInAsync(user, password, false,false);
            //List<Claim> claims = new List<Claim>() {
            //     new Claim("userName",name)
            //};

            //这里可以随意加入自定义的参数,key可以自己随便起
            var claims = new[]
            {
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
                    new Claim(ClaimTypes.NameIdentifier, name)               
             };
            var token =  CreateAccessToken(claims);

            YMNSession.UserId = user.Id;
            YMNSession.UserName = user.UserName;
            YMNSession.TenantId = user.TenantId;
            return token;
        }

[HttpGet]
[Route("Get2")]
[Authorize("YMNPolicy")]
public ActionResult<IEnumerable<string>> Get2()
{
//这是获取自定义参数的方法

return new string[] { "只有授权的用户才能访问该接口", $"userName={YMNSession.UserName}" };
}

 
复制代码

 

2、增加异常处理

 

复制代码
 public static void UseMyExceptionHandler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            app.UseExceptionHandler(builder => {

                builder.Run(async context =>
                {
                    context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    context.Response.ContentType = "application/json";
                    var ex = context.Features.Get<IExceptionHandlerFeature>();
                    if (ex != null)
                    {
                        //记录日志
                        var logger = loggerFactory.CreateLogger("YmnFrmaworkExceptionHandler");
                        logger.LogDebug(500, ex.Error, ex.Error.Message);
                    }
                    await context.Response.WriteAsync(ex?.Error?.Message ?? "错误了");
                });
            });
        }
复制代码

 

 

3、增加授权策略

复制代码
       /// <summary>
        /// 验证策略
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, YMNPolicy requirement)
        {
            //赋值用户权限
            var userPermissions = requirement.UserPermissions;
            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
            //请求Url
            var questUrl = httpContext.Request.Path.Value.ToUpperInvariant();
            //是否经过验证
            var isAuthenticated = httpContext.User.Identity.IsAuthenticated;
            if (isAuthenticated)
            {
                if (userPermissions.GroupBy(g => g.Url).Any(w => w.Key.ToUpperInvariant() == questUrl))
                {
                    //用户名
                    var userName = httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.NameIdentifier).Value;
                    if (userPermissions.Any(w => w.UserName == userName && w.Url.ToUpperInvariant() == questUrl))
                    {
                        //处理程序使用 AuthorizationHandlerContext 类来标记是否已满足要求:
                        context.Succeed(requirement);
                    }
                    else
                    {
                        //无权限跳转到拒绝页面
                        httpContext.Response.Redirect(requirement.DeniedAction);
                    }
                }
                else
                {
                    context.Succeed(requirement);
                }
            }
            return Task.CompletedTask;
        }
复制代码

 

posted on   topguntopgun  阅读(356)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示