2016-11-06 11 views
0

私のプロジェクトをasp.netコアに移行しています。私のコントローラのCustomAuthorization属性を移行することに悩まされています。ここに私のコードです。ASP.NET CoreのHandleUnauthorizedRequestをオーバーライドする方法

public class CustomAuthorization : AuthorizeAttribute 
{ 
    public string Url { get; set; } 

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery); 
     } 
     else if (!Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) 
     { 
      filterContext.Result = new ViewResult 
      { 
       ViewName = "AcessDenied" 
      }; 
     } 
     else 
     { 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
    } 
} 

は、私は基本的に私は役割が満たされていないときに別のログインページにリダイレクトするためにそれを使用することができますので、私のコントローラ

[CustomAuthorization(Url = "/Admin/Account/Login", Roles = "Admin")] 
public abstract class AdminController : Controller { } 

にそれを使用しました。私はいくつかの領域があり、それぞれに異なるログインページがあります。私は、管理コントローラ上で、その後CookieAuthenticationOptionsに

[Area("Admin")] 
[Authorize(ActiveAuthenticationSchemes = "Admin", Roles = "Admin")] 

このような
services.Configure<CookieAuthenticationOptions>(options => 
{ 
    options.AuthenticationScheme = "Admin"; 
    options.LoginPath = "/Admin/Account/Login"; 
}); 

を使用してみましたが、私がログインした後に、それはまだで取得傾ける。

+0

は、あなたがこのコードをステップ実行しようとしていますか?実行されますか?それはどこで失敗するのですか? – Darkonekt

+0

http://stackoverflow.com/questions/31464359/custom-authorizeattribute-in-asp-net-5-mvc-6をご覧ください –

答えて

1

私は1つに似た何かをやっています私のプロジェクトのこの回答はAuthorizeAttributeを使用していません。それはGoogleの検索からここに着陸するのを助けるかもしれない。 私の場合は、カスタムロジックに基づいて認可するために使用しています。

まず私のカスタム属性クラス:

public class CustomAuthorizationAttribute : ActionFilterAttribute 
{ 
    private readonly IMyDepedency _dp; 
    public CustomAuthorizationAttribute(IMyDepedency dp) 
    { 
     _dp = dp; 
    } 
    public override void OnActionExecuting(ActionExecutingContext context) 
    { 
     var isValid = false; 
     //write my validation and authorization logic here 
     if(!isValid) 
     { 
      var unauthResult = new UnauthorizedResult(); 

      context.Result = unauthResult;     
     } 

     base.OnActionExecuting(context); 
    } 
} 

私はこのように私のコントローラを飾る:

私のスタートアップクラスで次に
[ServiceFilter(typeof (CustomAuthorizationAttribute))] 

public void ConfigureServices(IServiceCollection services) 
{ 
    // Add framework services. 
    services.AddMvc(); 

    // my other stuff that is not relevant in this post 

    // Security 
    services.AddTransient<CustomAuthorizationAttribute>(); 
} 
関連する問題