簡體   English   中英

Azure 使用自定義授權屬性進行 AD 身份驗證

[英]Azure AD Authentication using custom Authorize Attribute

我正在開發使用 .NET Framework 4.8 構建的 web 應用程序。 該應用程序的一側面向公眾,一側面向管理員。 該應用程序在 Azure 上注冊,我正在嘗試使用 Azure AD 組對用戶進行身份驗證和授權。

我在 aa Startup.Auth.cs部分 class 中設置了 Azure 身份驗證的中間件。 部分 class 中的代碼如下所示。

要訪問管理員端,用戶必須在 URL 中鍵入 /admin,這將 go 到管理員 controller。

我在 Admin Controller 中使用具有特定角色的自定義授權屬性。 它在 AdminController class 初始化之前使用。

自定義授權 class 代碼如下所示。

在本地,該應用程序似乎工作正常,它允許授權屬性中指定的組中的人並重定向那些無法訪問 Home 的人,就像我們想要的那樣。

當我們將代碼發布到生產環境時,當用戶嘗試將 go 發送到管理員端時,應用程序總是將用戶帶回家。

redirectURI 設置為“https://example.com/admin”,並添加到 Azure 中的應用程序中。

在管理員 controller 中使用 Authorize 屬性允許屬於租戶的 Azure AD 的任何人。

如果我遺漏了什么或您的想法,請告訴我

Startup.Auth.cs

public partial class Startup
{
     private static string clientId = ConfigurationManager.AppSettings["ClientId"];

     private static string aadInstance = ConfigurationManager.AppSettings["AADInstance"];

     private static string tenantId = ConfigurationManager.AppSettings["TenantId"];

     private static string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];

     private static string authority = aadInstance + tenantId + "/v2.0";

     public void ConfigurationAuth(IAppBuilder app)
     { 
         app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

         app.UseCookieAuthentication(new CookieAuthenticationOptions()); 

         app.UserOpenIdConnectAuthentication(
               new OpenIdConnectAuthenticationOptions()
               {
                  ClientId = clientId;
                  Authority = authority;
                  RedirectUri = redirectUri;
                  Notifications = new OpenIdConnectAuthenticationNotifications()
                  {
                     AuthenticationFailed = (context) => {
                          context.HandleResponse();
                          context.Response.Redirect("Home/index");
                          return Task.FromResult(0);
                     }
                  }
               });
     }
}

自定義授權屬性AuthorizeAttribute.cs

public class AuthorizeAD : AuthorizeAttribute
{
    private bool noPermission = false;

    protected override bool AuthorizationCore(HttpContextBase httpContext)
    {
         if(!httpContext.User.Identity.IsAuthenticated)
           return false;

         var roles = Roles.Trim().Split(',');

         if(roles.ToList().Exists(role => httpContext.User.IsInRole(role)))
         {
             return true;
         }

         else
         {
             noPermission = true;
             return false;
         }
    }

    protected override void HandleUnAuthorizedRequest(AuthorizationContext filterContext)
    {
        if(noPermission)
              filterContext.Result = new RedirectResult("Home/index");
        else
              base.HandleUnauthorizedRequest(filterContext);
     }

}

任何幫助、反饋或建議都會很棒。 先感謝您!

• 您可以capture the return URL using the request information instead of using the 'custom AuthorizeAttribute' which will make your 'returnURL' or redirect URI available within 'Request.QueryString[]' dictionary中可用。 此外,您需要在登錄視圖中添加以下內容以使其可操作,並在登錄表單中添加以下內容:-

@{
ViewBag.ReturnUrl = Request.QueryString["returnUrl"];
}

@using (Html.BeginForm("Login", "Account", new {returnUrl = ViewBag.ReturnUrl}, FormMethod.Post, new{@class="form-horizontal form-material", @onsubmit="return loading_event();", @id="loginForm"}))

請在下面的 SO 社區線程中找到更多參考和說明:-

自定義授權屬性,重定向到原始 URL

此外,由於您想使用具有特定角色的自定義 'AuthorizeAttribute' class 用於在 'AdminController' class 中進行訪問,因此您當然可以通過對 'AdminController' ZA2F21ED4F8EBC290ABCDBB4 中的操作利用基於角色的授權來使用它們: -

'Auth.cs' 中的字符串常量: -

 public static class RoleConstants
 {
  public const string Admin = "Admin";
  public const string Moderator = "Moderator";
  // more roles
  }

'AdminController' class 在上述常量包含后如下: -

[Authorize(Roles=RoleConstants.Admin+","+RoleConstants.Moderator)]
 public class AdminController : Controller
{
// ... 
}

請找到以下鏈接以獲取有關上述內容的更多信息:-

https://www.telerik.com/blogs/creating-custom-authorizeattribute-asp-net-core

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM