/// <summary>
        /// Returns an error message if the jwt token is missing or the token validation failed.
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public static async Task ChallengeFailedResponse(JwtBearerChallengeContext arg)
        {
            // Important: Skip default error handling!
            arg.HandleResponse();

            // Check first if response was already handled in AuthenticationFailed()
            if (!arg.Response.HasStarted)
            {
                var error = new MyProblemDetails(arg.HttpContext)
                {
                    Title     = "Authentication Error",
                    Status    = StatusCodes.Status401Unauthorized,
                    Type      = "https://www.my-error-portal.com/myproject/401",
                    ErrorCode = "401"
                };

                if (string.IsNullOrWhiteSpace(arg.Error))
                {
                    error.Detail = "Authorization header is missing.";
                }
                else
                {
                    var logger = arg.HttpContext.RequestServices.GetRequiredService <ILogger <JwtEventHelper> >();
                    logger.LogError($"Authentication failed with error: {arg.Error}.");
                    error.Detail = $"Authentication failed with error: {arg.Error}.";
                }

                // Add error message to response
                await WriteResponse(error, arg.Response, StatusCodes.Status401Unauthorized);
            }
        }
Esempio n. 2
0
 public override Task Challenge(JwtBearerChallengeContext context)
 {
     if (context.AuthenticateFailure != null)
     {
         WriteExceptionToHttpResponse(context.HttpContext.Response, ErrorStatusCode.AuthorizationFailed);
         context.HandleResponse();
     }
     return(Task.CompletedTask);
 }
Esempio n. 3
0
        private static Task OnChallenge(JwtBearerChallengeContext context, string[] areas)
        {
            if (context.AuthenticateFailure != null)
            {
                string location = CreateReturnLocation(context, areas);

                context.Response.Headers.Append(HeaderNames.Location, location);
                context.Response.Headers.Append(HeaderNames.WWWAuthenticate, context.Options.Challenge);

                if (context.Request.AcceptsJsonResponse())
                {
                    return(Task.Factory.StartNew(() =>
                    {
                        context.Response.StatusCode = 401;
                        context.HandleResponse();
                    }));
                }
            }

            return(Task.Factory.StartNew(() => context.HandleResponse()));
        }
Esempio n. 4
0
 public override Task Challenge(JwtBearerChallengeContext context)
 {
     if (context.AuthenticateFailure != null)
     {
         var    json  = Newtonsoft.Json.JsonConvert.SerializeObject(ErrorStatusCode.AuthorizationFailed.StatusCode);
         byte[] bytes = Encoding.UTF8.GetBytes(json);
         context.HttpContext.Response.StatusCode = 401;
         context.HttpContext.Response.Headers.Add("Content-Type", "application/json");
         context.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
         context.HandleResponse();
     }
     return(Task.CompletedTask);
 }
Esempio n. 5
0
        public override Task Challenge(JwtBearerChallengeContext context)
        {
            context.HandleResponse();

            var payload = new JObject
            {
                ["error"]             = context.Error,
                ["error_description"] = context.ErrorDescription,
                ["error_uri"]         = context.ErrorUri
            };

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = 401;

            return(context.Response.WriteAsync(payload.ToString()));
        }
Esempio n. 6
0
        /// <summary>
        /// 没有JwtToken时触发
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task Challenge(JwtBearerChallengeContext context)
        {
            context.Response.Clear();
            context.Response.StatusCode  = 200;
            context.Response.ContentType = "application/json";
            BaseResponse response = new BaseResponse()
            {
                success      = false,
                errorCode    = nameof(ExceptionCode.EC107).GetCode().ToString(),
                errorMessage = ExceptionCode.EC107
            };

            context.Response.WriteAsync(JsonConvert.SerializeObject(response));
            context.HandleResponse();
            return(base.Challenge(context));
        }
Esempio n. 7
0
        ///// <summary>
        ///// 接收时
        ///// </summary>
        ///// <param name="context"></param>
        ///// <returns></returns>
        //public override Task MessageReceived(MessageReceivedContext context)
        //{
        //    context.Token = context.Request.Headers["Authorization"];
        //    return Task.CompletedTask;
        //}

        ///// <summary>
        ///// TokenValidated:在Token验证通过后调用。
        ///// </summary>
        ///// <param name="context"></param>
        ///// <returns></returns>
        //public override Task TokenValidated(TokenValidatedContext context)
        //{

        //    return Task.CompletedTask;
        //}
        #endregion


        /**注释原因:token过期AuthenticationFailed执行完后 Challenge方法会报System.InvalidOperationException: StatusCode cannot be set because the response has already started**/
        ///// <summary>
        ///// AuthenticationFailed: 认证失败时调用。触发场景:1.token过期(一定)  使用时一定要在 Controller或方法名上加[Authorize]
        ///// </summary>
        ///// <param name="context"></param>
        ///// <returns></returns>
        //public override async Task AuthenticationFailed(AuthenticationFailedContext context)
        //{
        //    context.Response.StatusCode = StatusCodes.Status200OK;
        //    context.Response.ContentType = "application/json";
        //    var response = new HResponse()
        //    {
        //        Success = false,
        //        ErrorCode = nameof(ErrorInfo.E100001).GetErrorCode(),
        //        ErrorMsg = ErrorInfo.E100001
        //    };
        //    await context.Response.WriteAsync(H_JsonSerializer.Serialize(response));
        //}


        /// <summary>
        /// Challenge: 服务器可以用来针对客户端的请求发送质询(challenge)。 触发场景:1.token值为空(一定) 2.token过期(一定) 2.token值有误 (一定)。 使用时一定要在 Controller或方法名上加[Authorize]
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task Challenge(JwtBearerChallengeContext context)
        {
            context.HandleResponse(); //此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦,必须,不加的话 控制台里会报异常System.InvalidOperationException: StatusCode cannot be set because the response has already started
            context.Response.StatusCode  = StatusCodes.Status200OK;
            context.Response.ContentType = "application/json";
            var response = new H_Response()
            {
                Success   = false,
                ErrorCode = H_Error.E100001.Key,
                ErrorMsg  = H_Error.E100001.Value
            };

            var options = new JsonSerializerOptions
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, //解决中文乱码
                PropertyNamingPolicy = null                            //PropertyNamingPolicy = JsonNamingPolicy.CamelCase //开头字母小写 默认
            };

            await context.Response.WriteAsync(JsonSerializer.Serialize(response, options));
        }
Esempio n. 8
0
        public async Task OnAuthChallenge(JwtBearerChallengeContext ctx)
        {
            await ctx.Response.WriteAsJsonAsync(new ApiResponse <string>(false, 401, "Token is invalid"));

            ctx.HandleResponse();
        }