asp.net-core – 如何使用ASP.NET Core中的JWT授权重定向到401上
发布时间:2020-12-16 00:00:40 所属栏目:asp.Net 来源:网络整理
导读:我在我的Startup.cs中有这个JWT授权配置: services.AddAuthentication(opts ={ opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultAuthentic
我在我的Startup.cs中有这个JWT授权配置:
services.AddAuthentication(opts => { opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(opts => { opts.RequireHttpsMetadata = false; opts.SaveToken = true; opts.TokenValidationParameters = new TokenValidationParameters() { IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("my_secret_key")),ValidIssuer = "iss",ValidAudience = "aud",ValidateIssuerSigningKey = true,ValidateLifetime = true }; }); 我的HomeController有[Authorize]属性.因此,在访问Home / Index时,我收到了401响应,并且我看到了一个空白页面.我想重定向到我的帐户/登录页面,但我不知道该怎么做. 我读到这不应该自动重定向,因为如果它们未被授权然后你重定向它们对API调用没有意义,那么我将如何将它们带到401上的登录页面的正确方法是什么. 请记住,在这个项目中,我同时拥有带有[Authorize]属性的Web API和Action方法,因此我只需要在它是一个action方法时重定向. 解决方法
您可以使用
StatusCodePages middleware.在Configure方法中添加以下内容:
app.UseStatusCodePages(async context => { var request = context.HttpContext.Request; var response = context.HttpContext.Response; if (response.StatusCode == (int)HttpStatusCode.Unauthorized) // you may also check requests path to do this only for specific methods // && request.Path.Value.StartsWith("/specificPath") { response.Redirect("/account/login") } });
这与API调用有关,它返回页面以外的数据.假设您的应用在后台调用API.将操作重定向到登录页面没有帮助,因为应用程序不知道如何在没有用户参与的情况下在后台验证自身. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 当前上下文错误中不存在名称“Url”
- asp.net – FileUpload.hasFile始终为False
- asp.net-mvc – MapMvcAttributeRoutes:此方法不能在应用程
- 未能加载文件或程序集或它的某一个依赖项
- asp.net-mvc – 在VS 2015中添加视图上下文菜单非常慢
- asp.net – 优雅地停止fastcgi-mono-server,网站内容更新,无
- asp.net-mvc-3 – 将输入值传递给Action(ASP.Net MVC 3)
- asp.net-mvc – 获取错误 – “@”字符后面的意外“if”关键
- asp.net-mvc-5 – 当我点击外部提供商按钮时,为什么我的网站
- asp.net-mvc – 如何从PropertyInfo或MetaData中检测[NotMa
推荐文章
站长推荐
- asp.net – 确定所需服务器数量的最佳方法
- asp.net-mvc-3 – 当用户需要再次登录时,Ajax.Ac
- C# 超高速高性能写日志 代码开源
- asp.net – 将Dictionary加入querystring的最快方
- asp.net-mvc – 何时使用RedirectToAction和哪里
- Asp.Net MVC EnableClientValidation不起作用
- asp.net-mvc – 如何在ASP.NET MVC中使用编译的全
- asp.net-mvc – DotNetOpenAuth简单演示,MVC和Ra
- asp.net-core – 如何从.net核心连接到Sybase数据
- asp.net-core – 运行Add-Migration时无法加载程
热点阅读