User Roles

Posted 191 days ago by tolaes
0

I added the following code in my Startup.cs so that I can access app roles I created in my registered application in Azure AD.  

// Startup.cs

public void ConfigureServices(IServiceCollection services)

{

            // [removed for brevity]

            // This is required to be instantiated before the OpenIdConnectOptions starts getting configured.

            // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.

            // 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles'

            // This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token

            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            // The following lines code instruct the asp.net core middleware to use the data in the "groups" claim in the Authorize attribute and User.IsInrole()

            // See https://docs.microsoft.com/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 for more info.

            services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>

            {

                // Use the groups claim for populating roles

                options.TokenValidationParameters.RoleClaimType = "roles";

            });

           

            // [removed for brevity]

}

User.IsInRole("UserReaders"); // In methods

 

When I try to access the role using the following code [user.IsInRole("Admin")] , it does not seem to recognize the "Admin" role. I confirmed this is the user/app role I am assigned to but not working.  Is there something I am doing wrong or missing?  Any help would be appreciated!

 

 //Used to determine user role
        var user = (await authenticationStateTask).User;


        if (args.RequestType.Equals(Syncfusion.Blazor.Grids.Action.BeginEdit))
        {
            //check user role
            //if (user.IsInRole("Claim_Reviewer"))
            if (user.IsInRole("Admin"))
            {
                var SelectedRowsForSave = await DefaultGrid.GetSelectedRecords();
                var selectedcount = SelectedRowsForSave.Count();
                //Only allow to edit 1 record at time.
                if (selectedcount > 1)
                {
                    args.Cancel = true;
                    IsVisible_EditOneRecord_Only = true;
                }


            }
            else
            {
                //Close edit dialog and show no permissions dialog box
                args.Cancel = true;
                IsVisible_NoPermissions = true;
            }

        }
  • 0

    Have you added roles to the default identity in the ConfigureServices method as well? Something like AddRoles mentioned below

    services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    Posted 189 days ago by selliott
  • 0

    Yes I do.  This is my ConfigureServices code:

     

    public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("DefaultConnection")));
                services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                    .AddRoles<IdentityRole>()
                    .AddEntityFrameworkStores<ApplicationDbContext>();
    
                services.AddRazorPages();
                services.AddServerSideBlazor();
                services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
                services.AddSingleton<WeatherForecastService>();
                services.AddRazorPages();
                services.AddServerSideBlazor();
                services.AddSingleton<WeatherForecastService>();
                services.AddSyncfusionBlazor();
                services.AddTransient<ISqlDataAccess, SqlDataAccess>();
                services.AddTransient<IPeopleData, PeopleData>();
                services.AddTransient<ITransactions, Transactions>();
                services.AddTransient<IDistributor, Distributor>();
                services.AddTransient<IInvoiceWeek, InvoiceWeek>();
                services.AddTransient<IProcessingStatus, ProcessingStatus>();
                services.AddTransient<IUploadFile, UploadFile>();
                services.AddTransient<IExceptionCodes, ExceptionCodes>();
                services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
                services.AddHttpContextAccessor();
                services.AddAuthentication();
                var emailConfig = Configuration
                 .GetSection("EmailConfiguration")
                 .Get<EmailConfiguration>();
                services.AddSingleton(emailConfig);
    
                services.AddScoped<IEmailSender, EmailSender>();
    
                //Tremor 12/09/2021
                services.AddAuthentication("Cookies")
                    .AddCookie(opt =>
                    {
                        opt.Cookie.Name = "AuthCookie";
                    })
                    .AddMicrosoftAccount(opt =>
                    {
                        opt.SignInScheme = "Cookies";
                        opt.ClientId = Configuration["Microsoft:Id"];
                        opt.ClientSecret = Configuration["Microsoft:Secret"];
                    });
    
               
                //Tremor 12/09/2021
    
                // This is required to be instantiated before the OpenIdConnectOptions starts getting configured.
                // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.
                // 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles'
                // This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
                JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
    
                // The following lines code instruct the asp.net core middleware to use the data in the "groups" claim in the Authorize attribute and User.IsInrole()
                // See https://docs.microsoft.com/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 for more info.
                
                services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
                {
                    
                    // Use the groups claim for populating roles
                    options.TokenValidationParameters.RoleClaimType = "roles";
                });
    
                // Adding authorization policies that enforce authorization using Azure AD roles. Polices defined in seperate classes.
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
                    options.AddPolicy("Claim_Reader", policy => policy.RequireRole("Claim_Reader"));
                    options.AddPolicy("Claim_Reviewer", policy => policy.RequireRole("Claim_Reviewer"));
                    options.AddPolicy("Claim_Credit", policy => policy.RequireRole("Claim_Credit"));
                    
                });
    
    
                
            }
    Posted 189 days ago by tolaes
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 3
An error has occurred. This application may no longer respond until reloaded. Reload 🗙