繁体   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