I am developing role based authorization. After role is successfully defined with User.AddIdentity it disappears when I exit the page.
[AllowAnonymous]
[HttpPost]
public IActionResult Index(User user)
{
try
{
var currentUser = _UserService.login(user, _context);
if (currentUser.userID != 0)
{
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(1);
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, currentUser.NAME_SURNAME),
new Claim(ClaimTypes.Role, "Admin")
},
"ApplicationCookie");
User.AddIdentity(new ClaimsIdentity(identity));
var isin = User.IsInRole("Admin");
var cacheValue = _UserService.stringToMd5(currentUser.NAME_SURNAME);
Response.Cookies.Append("login_cache", cacheValue, options);
TempData["error"] = null;
return RedirectToAction("index", "home");
}
else
{
TempData["error"] = "Kullanıcı adı yada şifre yanlıştır.";
return RedirectToAction("index", "home");
}
}
catch(Exception ex){
TempData["error"] = ex.Message;
//TempData["error"] = "User not found.";
return RedirectToAction("index", "home");
}
}
[Area("Admin")]
[Authorize(Roles = "Admin")]
public class FaqController : Controller
{
....
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60);
});
services.AddMvc();
services.AddDbContext<ModelContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "admin",
template: "{area}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}