开源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 2020-02-06 18:50  topguntopgun  阅读(354)  评论(0编辑  收藏  举报

导航