c# – 用于web-api触发重定向的Asp.net核心授权
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 用于web-api触发重定向的Asp.net核心授权,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2129字,纯文字阅读大概需要4分钟。
内容图文
![c# – 用于web-api触发重定向的Asp.net核心授权](/upload/InfoBanner/zyjiaocheng/810/144f1f29940d4edaad069027e1486512.jpg)
我尝试使用SPA开始使用asp.net核心Web应用程序.
我已经通过教程构建了所有内容.所以我设置了这样的授权:
app.UseIdentity()
.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
我有web-api控制器:
[Route("Somewhere")]
[Produces("application/json")]
[Authorize()]
public class MyControllerController : Controller
{
[HttpGet]
public async Task<IEnumerable<Something>> GetSomething()
{
//....
}
}
和授权功能:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model)
{
//...
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return Redirect("somewhere");
}
//...
}
但是当我在JS中调用我的webapi端点时,我会收到重定向到登录页面而不是401状态.
我已经开始调查并在stackoverflow上找到答案,我必须将false设置为AutomaticChallenge并删除.UseIdentity().但是当我这样做时,我的[POST] AccountController.Login方法停止在线工作 – var result = await _signInManager.PasswordSignInAsync(model.Email,model.Password,model.RememberMe);异常 – 没有配置身份验证处理程序来处理该方案:Identity.Application.
我想在我的MVC控制器中接收重定向,但是在没有授权的情况下从Webapi端点接收401/403.如何从AuthorizeAttribute为MVC和WebApi控制器实现不同的行为?
谢谢你的任何进步.
解决方法:
Micha?Dymel写了一篇关于这篇文章的博文:https://devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/
他没有将AutomaticChallenge设置为false,而是使用IdentityOptions拦截重定向到登录视图,并在请求URL以“/ api /”段开头时拒绝它.要实现此目的,您应该修改Startup.ConfigureServices方法,如下所示:
services.AddIdentity<User, Role>(identityOptions =>
{
identityOptions.Cookies.ApplicationCookie.Events =
new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api") &&
context.Response.StatusCode == (int) HttpStatusCode.OK)
context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
else
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
}
};
});
内容总结
以上是互联网集市为您收集整理的c# – 用于web-api触发重定向的Asp.net核心授权全部内容,希望文章能够帮你解决c# – 用于web-api触发重定向的Asp.net核心授权所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。