zoukankan      html  css  js  c++  java
  • 开源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;
            }
  • 相关阅读:
    [JavaScript] 数组去重
    [JavaScript] console.log只在查看时才会读取这个打印的对象,并把此刻相关属性和值显示出来
    [Vuejs] 点击单选框触发两次点击事件的处理
    [Vuejs] 给ref赋值需要注意的问题
    [Vuejs] Vue解决代理设置导致浏览器Session丢失的问题
    [Vuejs] 在vue各个组件中应用全局scss变量
    [JavaScript] 跳出循环方法总结
    [JavaScript] 根据指定宽度截取字符串
    [Element-UI] 使用Element-UI的DateTimePicker组件报错:Cannot read property 'getHours' of undefined
    [Vuejs] 组件 v-if 和 v-show 切换时生命周期钩子的执行
  • 原文地址:https://www.cnblogs.com/topguntopgun/p/12269837.html
Copyright © 2011-2022 走看看