【问题标题】:Asp.net web api : redirect unauthorized requst to forbidden pageAsp.net web api:将未经授权的请求重定向到禁止页面
【发布时间】:2017-08-18 09:10:59
【问题描述】:

我试图将未经授权的请求重定向到某个禁止页面,但我在响应正文中收到禁止页面,我该如何解决这个问题?

这是我的 StartUp 课程:

app.CreatePerOwinContext(StoreContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
     ExpireTimeSpan = TimeSpan.FromDays(30),
});

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

我试图达到的方法是:

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public string GetCurrentUsername()
    {
        return UserManager.FindByEmail(User.Identity.Name).Name;
    }

我已经尝试过这些东西:

  • 从 cookieOptions 中移除 LoginPath 以返回 401
  • 创建自定义授权属性

顺便说一句,我使用 Angular,我认为这个问题与 ajax 调用有关......

【问题讨论】:

  • 你检查我下面的答案了吗?

标签: c# asp.net angularjs authorization identity


【解决方案1】:

您可以扩展授权属性来指定禁止页面。 像这样:

添加一个名为 AuthorizationAttribute 的新类,它继承自 AuthorizeAttribute 类。然后覆盖这2个方法

public class AuthorizationAttribute : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
      //check if user in in role admin and if yes then return true, else return false. Once it returns false, then HandleUnauthorizedRequest will be triggered automatically
      return userManager.IsUserInAdminRole(username);
   }

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
   {
      filterContext.Result = new RedirectResult("~/Error/ForbiddenPage");
   }
}

在你的方法中,使用新的 AuthorizationAttribute 类:

    [HttpGet]
    [Authorization] //You can just write Authorization without the word Attribute
    public string GetCurrentUsername()
    {
        return UserManager.FindByEmail(User.Identity.Name).Name;
    }

如果它与您的 ajax 相关,您可以在此处找到:github.com/ronnieoverby/mvc-ajax-auth 解决方案类似的问题

【讨论】:

  • 我之前检查过,但对我没有用:(
  • 查看此链接 github.com/ronnieoverby/mvc-ajax-auth
  • 你正在做一个ajax调用,所以最后它是相同的原理:)!!
  • 是的,我知道,这有点奇怪,为什么它不起作用……如果我尝试访问一些未经授权的页面,html 将显示没有数据,如果我重新加载页面,则会显示禁止页面向上 。我试图解决这个问题几个小时但不能!!!
  • 所以你的意思是,你被正确地重定向到 html 页面,但是禁止页面的内容只有在你刷新后才会出现。对吗?
猜你喜欢
  • 2017-04-12
  • 2013-11-19
  • 2011-06-17
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多