Skip to content

Commit 803c37d

Browse files
committed
Add sample for .NET Core 3.x.
1 parent 24b1b4f commit 803c37d

File tree

15 files changed

+317
-8
lines changed

15 files changed

+317
-8
lines changed

DynamicRoleBasedAuthorization.sln

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{BAAF
1515
EndProject
1616
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "netcore3.x", "netcore3.x", "{5FEB9007-1EFA-4814-BC15-DB0370B84E22}"
1717
EndProject
18-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleMvcWebApp", "samples\netcore3.x\SampleMvcWebApp\SampleMvcWebApp.csproj", "{0833E296-398F-42A4-9531-D125483AB019}"
18+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleMvcWebApp", "samples\netcore3.x\SampleMvcWebApp\SampleMvcWebApp.csproj", "{0833E296-398F-42A4-9531-D125483AB019}"
1919
EndProject
2020
Global
2121
GlobalSection(SolutionConfigurationPlatforms) = preSolution

samples/netcore3.x/SampleMvcWebApp/Areas/Access/Controllers/RoleController.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ public async Task<ActionResult> Create(RoleViewModel viewModel)
7878

7979
var roleAccess = new RoleAccess
8080
{
81-
Controllers = viewModel.SelectedControllers,
81+
Controllers = viewModel.SelectedControllers.ToList(),
8282
RoleId = role.Id
8383
};
8484
await _roleAccessStore.AddRoleAccessAsync(roleAccess);
@@ -150,7 +150,7 @@ public async Task<ActionResult> Edit(string id, RoleViewModel viewModel)
150150

151151
var roleAccess = new RoleAccess
152152
{
153-
Controllers = viewModel.SelectedControllers,
153+
Controllers = viewModel.SelectedControllers?.ToList(),
154154
RoleId = role.Id
155155
};
156156
await _roleAccessStore.EditRoleAccessAsync(roleAccess);
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Identity;
3+
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.EntityFrameworkCore;
5+
using SampleMvcWebApp.Areas.Access.Models;
6+
using SampleMvcWebApp.Data;
7+
using System.Collections.Generic;
8+
using System.ComponentModel;
9+
using System.Linq;
10+
using System.Threading.Tasks;
11+
12+
namespace SampleMvcWebApp.Areas.Access.Controllers
13+
{
14+
[Area("Access"), Authorize]
15+
[DisplayName("User Role Management")]
16+
public class UserRoleController : Controller
17+
{
18+
private readonly ApplicationDbContext _dbContext;
19+
private readonly RoleManager<IdentityRole> _roleManager;
20+
private readonly UserManager<IdentityUser> _userManager;
21+
22+
public UserRoleController(
23+
ApplicationDbContext dbContext,
24+
RoleManager<IdentityRole> roleManager,
25+
UserManager<IdentityUser> userManager
26+
)
27+
{
28+
_roleManager = roleManager;
29+
_userManager = userManager;
30+
_dbContext = dbContext;
31+
}
32+
33+
// GET: Access
34+
[DisplayName("User List")]
35+
public async Task<ActionResult> Index()
36+
{
37+
var query = await (
38+
from user in _dbContext.Users
39+
join ur in _dbContext.UserRoles on user.Id equals ur.UserId into userRoles
40+
from userRole in userRoles.DefaultIfEmpty()
41+
join rle in _dbContext.Roles on userRole.RoleId equals rle.Id into roles
42+
from role in roles.DefaultIfEmpty()
43+
select new { user, userRole, role }
44+
).ToListAsync();
45+
46+
var userList = new List<UserRoleViewModel>();
47+
foreach (var grp in query.GroupBy(q => q.user.Id))
48+
{
49+
var first = grp.First();
50+
userList.Add(new UserRoleViewModel
51+
{
52+
UserId = first.user.Id,
53+
UserName = first.user.UserName,
54+
Roles = first.role != null ? grp.Select(g => g.role).Select(r => r.Name) : new List<string>()
55+
});
56+
}
57+
58+
return View(userList);
59+
}
60+
61+
// GET: Access/Edit
62+
[DisplayName("Edit User Roles")]
63+
public async Task<ActionResult> Edit(string id)
64+
{
65+
var user = await _userManager.FindByIdAsync(id);
66+
if (user == null)
67+
return NotFound();
68+
69+
var userRoles = await _userManager.GetRolesAsync(user);
70+
var userViewModel = new UserRoleViewModel
71+
{
72+
UserId = user.Id,
73+
UserName = user.UserName,
74+
Roles = userRoles
75+
};
76+
77+
var roles = await _roleManager.Roles.ToListAsync();
78+
ViewData["Roles"] = roles;
79+
80+
return View(userViewModel);
81+
}
82+
83+
// POST: Access/Edit
84+
[HttpPost]
85+
[ValidateAntiForgeryToken]
86+
public async Task<ActionResult> Edit(UserRoleViewModel viewModel)
87+
{
88+
if (!ModelState.IsValid)
89+
{
90+
ViewData["Roles"] = await _roleManager.Roles.ToListAsync();
91+
return View(viewModel);
92+
}
93+
94+
var user = _dbContext.Users.Find(viewModel.UserId);
95+
if (user == null)
96+
{
97+
ModelState.AddModelError("", "User not found");
98+
ViewData["Roles"] = await _roleManager.Roles.ToListAsync();
99+
return View();
100+
}
101+
102+
var userRoles = await _userManager.GetRolesAsync(user);
103+
await _userManager.RemoveFromRolesAsync(user, userRoles);
104+
await _userManager.AddToRolesAsync(user, viewModel.Roles);
105+
106+
return RedirectToAction("Index");
107+
}
108+
}
109+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using System.Collections.Generic;
2+
using System.ComponentModel.DataAnnotations;
3+
4+
namespace SampleMvcWebApp.Areas.Access.Models
5+
{
6+
public class UserRoleViewModel
7+
{
8+
[Required]
9+
public string UserId { get; set; }
10+
11+
public string UserName { get; set; }
12+
13+
public IEnumerable<string> Roles { get; set; }
14+
}
15+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
@model UserRoleViewModel
2+
@{
3+
ViewData["Title"] = "Edit User Access";
4+
var roles = (IEnumerable<IdentityRole>)ViewData["Roles"];
5+
}
6+
7+
@*@section header{
8+
<style>
9+
.form-horizontal .control-label {
10+
padding-top: 0;
11+
}
12+
</style>
13+
}*@
14+
15+
<h2>Edit User Access</h2>
16+
17+
<hr />
18+
<div class="row">
19+
<div class="col-md-6">
20+
<form asp-action="Edit">
21+
<div asp-validation-summary="All" class="text-danger"></div>
22+
<input type="hidden" asp-for="UserId" />
23+
<input type="hidden" asp-for="UserName" />
24+
25+
<div class="form-group row">
26+
<label asp-for="UserName" class="col-md-2 col-form-label"></label>
27+
<div class="col-md-10">
28+
<span class="form-control">@Html.DisplayFor(m => m.UserName)</span>
29+
</div>
30+
</div>
31+
32+
<div class="form-group">
33+
<label class="col-md-2 control-label">Roles</label>
34+
<div class="col-md-10">
35+
@foreach (var role in roles)
36+
{
37+
<label>
38+
<input type="checkbox" name="Roles[]" value="@role.Name"
39+
@if (Model?.Roles != null && Model.Roles.Contains(role.Name)) { <text> checked="checked" </text> } />
40+
&nbsp;@role.Name&nbsp;&nbsp;
41+
</label>
42+
}
43+
</div>
44+
</div>
45+
46+
<div class="form-group row">
47+
<div class="col-md-10">
48+
<input type="submit" class="btn btn-primary" value="Edit" />
49+
</div>
50+
</div>
51+
</form>
52+
</div>
53+
</div>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
@model IEnumerable<UserRoleViewModel>
2+
@{
3+
ViewData["Title"] = "User Role List";
4+
}
5+
6+
<h2>Access List</h2>
7+
8+
<div class="row">
9+
<div class="col-md-10">
10+
11+
<table class="table table-bordered">
12+
<thead>
13+
<tr>
14+
<th scope="col"> @Html.DisplayNameFor(m => m.UserName) </th>
15+
<th scope="col"> @Html.DisplayNameFor(m => m.Roles) </th>
16+
<th> </th>
17+
</tr>
18+
</thead>
19+
<tbody>
20+
@foreach (var user in Model)
21+
{
22+
<tr>
23+
<td>@Html.DisplayFor(m => user.UserName)</td>
24+
<td>
25+
@foreach (var role in user.Roles)
26+
{
27+
<span>@Html.DisplayFor(m => role) | </span>
28+
}
29+
</td>
30+
<td>
31+
<a asp-action="Edit" asp-route-id="@user.UserId">Edit</a>
32+
</td>
33+
</tr>
34+
}
35+
</tbody>
36+
</table>
37+
</div>
38+
</div>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Mvc;
3+
using System.ComponentModel;
4+
5+
namespace SampleMvcWebApp.Controllers
6+
{
7+
[Authorize]
8+
[DisplayName("Protected section 1")]
9+
public class ProtectedOneController : Controller
10+
{
11+
[DisplayName("List")]
12+
public IActionResult Index()
13+
{
14+
return View();
15+
}
16+
17+
[DisplayName("Detail")]
18+
public IActionResult Detail()
19+
{
20+
return View();
21+
}
22+
}
23+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Mvc;
3+
using System.ComponentModel;
4+
5+
namespace SampleMvcWebApp.Controllers
6+
{
7+
[Authorize]
8+
[DisplayName("Protected section 2")]
9+
public class ProtectedTwoController : Controller
10+
{
11+
[DisplayName("List")]
12+
public IActionResult Index()
13+
{
14+
return View();
15+
}
16+
17+
[DisplayName("Detail")]
18+
public IActionResult Detail()
19+
{
20+
return View();
21+
}
22+
}
23+
}

samples/netcore3.x/SampleMvcWebApp/RoleAccess.json

Lines changed: 0 additions & 2 deletions
This file was deleted.

samples/netcore3.x/SampleMvcWebApp/Startup.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,10 @@ public void ConfigureServices(IServiceCollection services)
2828

2929
services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = false)
3030
.AddEntityFrameworkStores<ApplicationDbContext>()
31+
.AddDefaultTokenProviders()
3132
.AddDefaultUI();
3233

33-
services.AddDynamicAuthorization(options => options.DefaultAdminUser = "[email protected]")
34+
services.AddDynamicAuthorization<ApplicationDbContext>(options => options.DefaultAdminUser = "[email protected]")
3435
.AddJsonStore(options => options.FilePath =
3536
@"D:\Workspace\Github\DynamicRoleBasedAuthorizationNETCore\samples\netcore3.x\SampleMvcWebApp\bin\Debug\netcoreapp3.1\RoleAccess.json");
3637

0 commit comments

Comments
 (0)