Azure AD 身份验证和授权

时间:2021-07-07 13:36:46

标签: authentication azure-active-directory authorization

我正在开发 Asp.net MVC 项目,此应用程序从 Azure AD 进行身份验证,但基于角色的授权存在问题,基于角色组中的操作未授权。我把我的代码放在这里,请检查并帮助我。联系操作未授权,我创建了安全类型的 Operator1 组并分配给用户 公共部分类启动{ 私有静态字符串 clientId = ConfigurationManager.AppSettings["ida:ClientId"]; 私有静态字符串 appKey = ConfigurationManager.AppSettings["ida:ClientSecret"]; 私有静态字符串 aadInstance =EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]); 私有静态字符串tenantId = ConfigurationManager.AppSettings["ida:TenantId"]; 私有静态字符串 postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

public static readonly string Authority = aadInstance + tenantId;

// 这是 AAD Graph API 的资源 ID。我们需要它来请求令牌来调用 Graph API。 string graphResourceId = "https://graph.windows.net";

public void ConfigureAuth(IAppBuilder app) { ApplicationDbContext db = new ApplicationDbContext();

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

app.UseCookieAuthentication(new CookieAuthenticationOptions());

app.UseOpenIdConnectAuthentication(
  new OpenIdConnectAuthenticationOptions {
    ClientId = clientId,
      Authority = Authority,
      PostLogoutRedirectUri = postLogoutRedirectUri,

      Notifications = new OpenIdConnectAuthenticationNotifications() {
        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
        AuthorizationCodeReceived = (context) => {
          var code = context.Code;
          ClientCredential credential = new ClientCredential(clientId, appKey);
          string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
          AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
          AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(
            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId).Result;

          return Task.FromResult(0);
        }
      }
  });

} }

2 个答案:

答案 0 :(得分:0)

查看下面的示例,它可以帮助您使用应用角色和角色声明向使用 Microsoft 标识平台登录用户的 ASP.NET Core Web 应用添加授权。

在此处了解更多信息:

https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/5-WebApp-AuthZ/5-1-Roles

答案 1 :(得分:0)

感谢您的回答,我上面的代码对我有用,只是我需要将应用程序注册为企业应用程序,我不知道为什么需要它,如果您有任何想法,请告诉我。