Create ASP.NET Core Razor Pages Project
On the Visual Studio, create new ASP.NET Core Web Application project
Select Empty Template
Click Ok button to Finish
Configurations
Open Startup.cs file and add new configurations as below:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace LearnASPNETCoreRazorPagesWithRealApps
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/login/signout";
options.AccessDeniedPath = "/accessdenied";
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc();
}
}
}
Create Razor View Imports
Select Views folder and right click to select Add\New Item Menu
Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish
In _ViewImports.cshtml file and TagHelpers library as below:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Entities Class
Create new folder named Entities. In this folder, create new class named Account.cs as below:
Account Entity
Create new class named Account.cs as below:
namespace LearnASPNETCoreRazorPagesWithRealApps.Entities
{
public class Account
{
public string Username { get; set; }
public string Password { get; set; }
public string[] Roles { get; set; }
}
}
Models Class
In Models folder, create new class named AccountModel.cs as below:
AccountModel.cs
using LearnASPNETCoreRazorPagesWithRealApps.Entities;
using System.Collections.Generic;
using System.Linq;
namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
public class AccountModel
{
private List<Account> accounts;
public AccountModel()
{
accounts = new List<Account>() {
new Account
{
Username = "acc1",
Password = "123",
Roles = new string[]{ "superadmin", "admin", "employee" }
},
new Account
{
Username = "acc2",
Password = "123",
Roles = new string[]{ "admin", "employee" }
},
new Account
{
Username = "acc3",
Password = "123",
Roles = new string[]{ "employee" }
}
};
}
public Account find(string username)
{
return accounts.SingleOrDefault(a => a.Username.Equals(username));
}
public Account login(string username, string password)
{
return accounts.SingleOrDefault(a => a.Username.Equals(username) && a.Password.Equals(password));
}
}
}
Security Manager
Create new folder named Security folder. In this folder, create new class named SecurityManager.cs as below:
SecurityManager Class
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using LearnASPNETCoreRazorPagesWithRealApps.Entities;
using System.Collections.Generic;
using System.Security.Claims;
namespace LearnASPNETCoreRazorPagesWithRealApps.Security
{
public class SecurityManager
{
public async void SignIn(HttpContext httpContext, Account account)
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, account.Username));
identity.AddClaim(new Claim(ClaimTypes.Name, account.Username));
identity.AddClaims(getUserClaims(account));
var principal = new ClaimsPrincipal(identity);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
}
public async void SignOut(HttpContext httpContext)
{
await httpContext.SignOutAsync();
}
private IEnumerable<Claim> getUserClaims(Account account)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, account.Username));
foreach (var role in account.Roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
return claims;
}
}
}
Index Razor Page
Create new folder named Pages. In this folder, create new Razor Page named Index as below:
Index.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}
Index.cshtml
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h3>Home Page</h3>
</body>
</html>
AccessDenied Razor Page
In Pages folder, create new Razor Page named AccessDenied as below:
AccessDenied.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
public class AccessDeniedModel : PageModel
{
public void OnGet()
{
}
}
}
AccessDenied.cshtml
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.AccessDeniedModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AccessDenied</title>
</head>
<body>
<h3>Access Denied</h3>
</body>
</html>
Login Razor Page
In Pages folder, create new Razor Page named Login as below:
Login.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using LearnASPNETCoreRazorPagesWithRealApps.Models;
using LearnASPNETCoreRazorPagesWithRealApps.Security;
namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
public class LoginModel : PageModel
{
public string Msg;
private SecurityManager securityManager = new SecurityManager();
public void OnGet()
{
}
public IActionResult OnPost(string username, string password)
{
AccountModel accountModel = new AccountModel();
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || accountModel.login(username, password) == null)
{
Msg = "Invalid";
return Page();
}
else
{
securityManager.SignIn(HttpContext, accountModel.find(username));
return RedirectToPage("Welcome");
}
}
}
}
Login.cshtml
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.LoginModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
</head>
<body>
<h3>Login Page</h3>
@Model.Msg
<form method="post" asp-page="login">
Username <input type="text" name="username" />
<br />
Password <input type="password" name="password" />
<br />
<input type="submit" value="Login" />
</form>
</body>
</html>
Welcome Razor Page
In Pages folder, create new Razor Page named Welcome as below:
Welcome.cshtml.cs
using LearnASPNETCoreRazorPagesWithRealApps.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
[Authorize(Roles = "superadmin,admin,employee")]
public class WelcomeModel : PageModel
{
public string UserId;
private SecurityManager securityManager = new SecurityManager();
public void OnGet()
{
UserId = User.FindFirst(ClaimTypes.Name).Value;
}
public IActionResult OnGetLogout()
{
securityManager.SignOut(HttpContext);
return RedirectToPage("Login");
}
}
}
Welcome.cshtml
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.WelcomeModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Welcome</title>
</head>
<body>
<h3>Welcome Page</h3>
Welcome @Model.UserId
<br />
<a asp-page="welcome" asp-page-handler="logout">Logout</a>
</body>
</html>
Work1 Razor Page
In Pages folder, create new Razor Page named Work1 as below:
Work1.cshtml.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
[Authorize(Roles = "superadmin")]
public class Work1Model : PageModel
{
public string UserId;
public void OnGet()
{
UserId = User.FindFirst(ClaimTypes.Name).Value;
}
}
}
Work1.cshtml
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.Work1Model
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Work 1</title>
</head>
<body>
<h3>Work 1</h3>
Welcome @Model.UserId
<br />
<a asp-page="login" asp-page-handler="logout">Logout</a>
</body>
</html>
Work2 Razor Page
In Pages folder, create new Razor Page named Work2 as below:
Work2.cshtml.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
[Authorize(Roles = "superadmin,admin")]
public class Work2Model : PageModel
{
public string UserId;
public void OnGet()
{
UserId = User.FindFirst(ClaimTypes.Name).Value;
}
}
}
Work2.cshtml
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.Work2Model
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Work2</title>
</head>
<body>
<h3>Work 2</h3>
Welcome @Model.UserId
<br />
<a asp-page="login" asp-page-handler="logout">Logout</a>
</body>
</html>
Work3 Razor Page
In Pages folder, create new Razor Page named Work3 as below:
Work3.cshtml.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
[Authorize(Roles = "superadmin,admin,employee")]
public class Work3Model : PageModel
{
public string UserId;
public void OnGet()
{
UserId = User.FindFirst(ClaimTypes.Name).Value;
}
}
}
Work3.cshtml
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.Work3Model
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Work3</title>
</head>
<body>
<h3>Work 3</h3>
Welcome @Model.UserId
<br />
<a asp-page="login" asp-page-handler="logout">Logout</a>
</body>
</html>
Structure of ASP.NET Core Razor Pages Project
Run Application
-
Open Index Razor Page with following url: http://localhost:1115
-
Test access Work1 razor page without login with url: http://localhost:1115/Work1, the control will go redirect to the login page
-
Test access Work2 razor page without login with url: http://localhost:1115/Work2, the control will go redirect to the login page
-
Test access Work3 razor page without login with url: http://localhost:1115/Work3, the control will go redirect to the login page
-
Test login with invalid account: username is abc and password is 456
-
Test login with valid account: username is acc2 and password is 123. This account have roles: admin and employee
-
Use acc2 has logged access Work1 razor page with url: http://localhost:1115/Work1
-
Use acc2 has logged access Work2 razor page with url: http://localhost:1115/Work2
-
Use acc2 has logged access Work3 razor page with url: http://localhost:1115/Work3