Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Identity example done for blog https:gavilan.blog
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using IdentityDemo.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
namespace IdentityDemo.Controllers
{
public class HomeController : Controller
{
private readonly UserManager<ApplicationUser> userManager;
private readonly RoleManager<IdentityRole> roleManager;
public HomeController(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager
)
{
this.userManager = userManager;
this.roleManager = roleManager;
}
public IActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
// get user's claims
var claims = User.Claims.ToList();
}
return View();
}
public async Task<IActionResult> About()
{
// Add user to the role
if (User.Identity.IsAuthenticated)
{
// await roleManager.CreateAsync(new IdentityRole("Admin")); // Creates the role
var user = await userManager.GetUserAsync(HttpContext.User);
await userManager.AddToRoleAsync(user, "Admin");
}
ViewData["Message"] = "Your application description page.";
return View();
}
[Authorize(Roles = "Admin")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.