0
votes

I am developing Asp.net MVC project, This app authenticating form Azure AD but problem with role based authorization, action not authorized base in the role group. I put my code here, please review and help me. Contact action not authorizing, I created Operator1 group of security type and assigned to user public partial class Startup { private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"]; private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]); private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"]; private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

public static readonly string Authority = aadInstance + tenantId;

// This is the resource ID of the AAD Graph API. We'll need this to request a token to call the 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);
        }
      }
  });

} }

1
I am using action filters like [Authorize(Roles = "Operator1")] public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); }Waqar Baryar

1 Answers

0
votes

Look into this sample below which helps you add authorization using app roles & roles claims to an ASP.NET Core web app that's signs-in users with the Microsoft identity platform.

Learn more here:

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