Skip to content

Instantly share code, notes, and snippets.

@gavilanch
Created April 2, 2018 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavilanch/6d5a491c89a2f06e36ed5d96254bc4ba to your computer and use it in GitHub Desktop.
Save gavilanch/6d5a491c89a2f06e36ed5d96254bc4ba to your computer and use it in GitHub Desktop.
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