Created
April 2, 2018 01:38
-
-
Save gavilanch/6d5a491c89a2f06e36ed5d96254bc4ba to your computer and use it in GitHub Desktop.
Identity example done for blog https:gavilan.blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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