コード例 #1
0
        /// <summary>
        /// 抛异常处理方式
        /// </summary>
        protected virtual async Task ThrowExceptionHandleAsync(AuthorizationHandlerContext context,
                                                               JsonWebTokenAuthorizationRequirement requirement)
        {
            var httpContext = (context.Resource as AuthorizationFilterContext)?.HttpContext;

            if (httpContext == null)
            {
                return;
            }
            // 未登录而被拒绝
            var result = httpContext.Request.Headers.TryGetValue("Authorization", out var authorizationHeader);

            if (!result || string.IsNullOrWhiteSpace(authorizationHeader))
            {
                throw new UnauthorizedAccessException("未授权,请传递Header头的Authorization参数");
            }
            var token = authorizationHeader.ToString().Split(' ').Last().Trim();

            if (!await _tokenStore.ExistsTokenAsync(token))
            {
                throw new UnauthorizedAccessException("未授权,无效参数");
            }
            if (!_tokenValidator.Validate(token, _options, requirement.ValidatePayload))
            {
                throw new UnauthorizedAccessException("验证失败,请查看传递的参数是否正确或是否有权限访问该地址。");
            }
            var isAuthenticated = httpContext.User.Identity.IsAuthenticated;

            if (!isAuthenticated)
            {
                return;
            }
            context.Succeed(requirement);
        }
        /// <summary>
        /// 执行中间件拦截逻辑
        /// </summary>
        /// <param name="context">Http上下文</param>
        public async Task Invoke(HttpContext context)
        {
            // 如果是匿名访问路径,则直接跳过
            if (_anonymousPathList.Contains(context.Request.Path.Value))
            {
                await _next(context);

                return;
            }

            var result = context.Request.Headers.TryGetValue("Authorization", out var authStr);

            if (!result || string.IsNullOrWhiteSpace(authStr.ToString()))
            {
                throw new UnauthorizedAccessException("未授权,请传递Header头的Authorization参数");
            }
            // 校验以及自定义校验
            result = _tokenValidator.Validate(authStr.ToString().Substring("Bearer ".Length).Trim(), _options,
                                              _validatePayload);
            if (!result)
            {
                throw new UnauthorizedAccessException("验证失败,请查看传递的参数是否正确或是否有权限访问该地址。");
            }
            await _next(context);
        }
        /// <summary>
        /// 执行中间件拦截逻辑
        /// </summary>
        /// <param name="context">Http上下文</param>
        public async Task Invoke(HttpContext context)
        {
            // 如果是匿名访问路径,则直接跳过
            if (_anonymousPathList.Contains(context.Request.Path.Value))
            {
                await _next(context);

                return;
            }
            var result = context.Request.Headers.TryGetValue("Authorization", out var authStr);

            if (!result || string.IsNullOrWhiteSpace(authStr.ToString()))
            {
                throw new UnauthorizedAccessException("未授权,请传递Header头的Authorization参数");
            }
            // 校验以及自定义校验
            var codeResult = _tokenValidator.Validate(authStr.ToString().Substring("Bearer ".Length).Trim(), _options,
                                                      _validatePayload);

            if (codeResult == Code.Ok)
            {
                await _next(context);
            }
            else
            {
                var content = new AuthorizeResult(codeResult, codeResult.Description());
                switch (codeResult)
                {
                case Code.Ok:
                    break;

                case Code.Unauthorized:
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.TokenInvalid:
                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.Forbidden:
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.NoFound:
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.MethodNotAllowed:
                    context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.HttpRequestError:
                    context.Response.StatusCode = (int)HttpStatusCode.NotAcceptable;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.Locked:
                    context.Response.StatusCode = (int)HttpStatusCode.Locked;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                case Code.Error:
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    await context.Response.WriteAsync(content.ToJson());

                    break;

                default:
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    await context.Response.WriteAsync(content.ToJson());

                    break;
                }
                return;
            }


            //if (!result)
            //{
            //    //var content = new AuthorizeResult(codeResult, codeResult.Description());
            //    //await context.Response.WriteAsync(content.ToJson());
            //    ////context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            //    //return;

            //    throw new UnauthorizedAccessException("验证失败,请查看传递的参数是否正确或是否有权限访问该地址。");
            //}

            //await _next(context);
        }