I am using .net core 2.0 and trying to do authorization using asp identity in a mvc website. (Authentication is done using Google OAuth).
Authentication is working fine i.e users can access controllers/views after logging in through google. But when I try adding a role("Admin") to a particular controller, I get unauthorized.
Setup reference : https://github.com/TahirNaushad/Fiver.Security.AspIdentity/ DB : MySql
Below is my startup configuration:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppIdentityDbContext>(options =>
options.UseMySql(configuration["DB_CONN"]));
services.AddIdentity<AppIdentityUser, AppIdentityRole>()
.AddEntityFrameworkStores<AppIdentityDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication().AddGoogle(googleOptions =>
{
googleOptions.ClientId = "******.apps.googleusercontent.com";
googleOptions.ClientSecret = "******";
googleOptions.SaveTokens = true;
googleOptions.AccessType = "offline";
});
services.Configure<IdentityOptions>(options =>
{
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+ ";
options.Lockout.AllowedForNewUsers = true;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.User.RequireUniqueEmail = true;
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Security/Login";
options.LogoutPath = "";
options.AccessDeniedPath = "/Security/AccessDenied";
options.SlidingExpiration = true;
options.Cookie = new CookieBuilder
{
HttpOnly = true,
Name = ".Test",
Path = "/",
SameSite = SameSiteMode.Lax,
SecurePolicy = CookieSecurePolicy.SameAsRequest
};
});
services.AddMvc();
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
Authorization using role:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace Test.Controllers
{
[Authorize(Roles = "Admin")]
public class MoviesController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
Note: 1. Entries are present in AspNetUsers, AspNetRoles and AspNetUserRoles 2. I checked online and found that roles should be present in Principal.Claims with claim type as roles but for me that is not true. Any help is appreciated. Thanks in advance!