3

I can't define my Admin, Company, Agency roles because

services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

is not working or is not defining and it gives me an error

Error   CS1061  'IServiceCollection' does not contain a definition for 'AddDefaultIdentity' and no accessible extension method 'AddDefaultIdentity' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

Here is my ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddControllersWithViews();
    services.AddDbContext<TradeTurkDBContext>();
    services.AddDefaultIdentity<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<TradeTurkDBContext>();

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(x =>
            {
                ...
            });
    services.AddMvc(config =>
        {
            ...
        });
}

And here is my using libraries

using BL.TradeTurk;
using DAL.TradeTurk;
using Entities.TradeTurk;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

Can anyone tell me which part I am missing?

I looked at that AddRoles part in the Microsoft sources and there is nothing different my code and their source code.

Here is Microsoft source down to the page.

BerkGarip
  • 534
  • 5
  • 18

3 Answers3

2

I think The problem was in the order of Authentication and Authorization in the pipeline, Authentication should always be placed before Authorization. Change your middleware order in Configure method like below:-

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            else
                app.UseExceptionHandler("/Home/Error");

            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
                
            app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Account}/{action=Login}/{id?}");
                });
}

Pritom Sarkar
  • 2,154
  • 3
  • 11
  • 26
  • my problem is not that. my problem is VisualStudio2019 is not defining my "services.AddDefaultIdentity() .AddRoles() .AddEntityFrameworkStores();" code – BerkGarip Feb 20 '21 at 19:04
  • ```Microsoft.AspNetCore.Identity.UI;``` add this library, I think it works. – Pritom Sarkar Feb 20 '21 at 19:16
  • its not even exist :( – BerkGarip Feb 20 '21 at 19:21
  • oops, Microsoft.AspNetCore.Identity. UI.Services are not available for ASP.NET Core 5.0 Preview. actually, I forgot you are using 5.0 version. https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs=visual-studio read this article. – Pritom Sarkar Feb 20 '21 at 19:32
  • i know, that is why im using ```Microsoft.AspNetCore.Identity.``` as u can see in my library down to the question. – BerkGarip Feb 20 '21 at 19:36
  • 1
    https://stackoverflow.com/questions/61619369/iservicecollection-does-not-contain-a-definition-for-adddefaultidentity Is not your answer which you want? – Pritom Sarkar Feb 20 '21 at 19:42
2

I did it in .net5 with customized identity as below:

  • create custom user and role:
public class AppUser : IdentityUser
{
}

public class AppRole : IdentityRole
{
}

public class AppUserRole : IdentityUserRole<string>
{
    public virtual AppUser User { get; set; }
    public virtual AppRole Role { get; set; }
}
  • Create custom db context:
public class ApplicationDbContext : IdentityDbContext<AppUser, AppRole, string, IdentityUserClaim<string>, AppUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    } 
}
  • Register custom db context and identity classes in startup:
services.AddDbContext<ApplicationDbContext>(options => //...);
services.AddIdentity<AppUser, AppRole>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultUI()
        .AddDefaultTokenProviders();
  • Finally define role based authorization:
services.AddAuthorization(ops =>
{
    ops.AddPolicy("RequireAdmins", policy => policy.RequireRole("Admins"));
});

services.AddRazorPages()
        .AddRazorPagesOptions(ops =>
        {
                ops.Conventions.AuthorizeFolder("/", "RequireAdmins");
        });
LazZiya
  • 5,286
  • 2
  • 24
  • 37
0

Try using services.AddIdentityCore().AddRoles();

Monu
  • 26
  • 2
  • its not defining that part ```services.AddDefaultIdentity()``` .it says "IServiceCollection does not contain a defination 'AddDefaultIdentity'"...... – BerkGarip Feb 20 '21 at 19:15