using Microsoft.AspNetCore.Authorization; namespace CookieAuthentication.Authorization { public class PermissionAuthorizationRequirement : IAuthorizationRequirement { public string[] Permissions { get; set; }
public PermissionAuthorizationRequirement(string[] permissions) { Permissions = permissions; } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; using System; using System.Threading.Tasks;
namespace CookieAuthentication.Authorization { public class PermissionFilter:Attribute, IAsyncAuthorizationFilter { public string[] permissions { get; set; }
public PermissionFilter(params string[] permissions) { this.permissions = permissions; }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { var authorizationService = context.HttpContext.RequestServices.GetRequiredService<IAuthorizationService>(); var authorizationResult = await authorizationService.AuthorizeAsync(context.HttpContext.User, null, new PermissionAuthorizationRequirement(permissions)); if (!authorizationResult.Succeeded) { // 如果授權失敗,設定為未授權 context.Result = new UnauthorizedResult(); } } } }
說明: 重點在21~27,使用authorizationService.AuthorizeAsync去認證權限,就會把資料傳到我們上面建立的PermissionAuthorizationHandler.cs裡面判斷。 如果最後判斷沒權限則設定context.Result = new UnauthorizedResult();表示禁止。
using CookieAuthentication.Authorization; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; namespace CookieAuthentication { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // 註冊需求和處理常式,套用自訂權限控制器 services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles();
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks;
namespace CookieAuthentication { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) {
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles();
using CookieAuthentication.Models; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks;
namespace CookieAuthentication.Controllers {
public class HomeController : Controller { private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) { _logger = logger; }
public IActionResult Index() { return View(); }
[Authorize] public IActionResult Privacy() { StringBuilder sb = new StringBuilder(); sb.AppendLine("<ul>");
<div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div>
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApplication1.Models;
namespace WebApplication1.ViewComponents { public class ShowUserInfo : ViewComponent { public async Task<IViewComponentResult> InvokeAsync(string number, string name,string tel) { Customer customer = new Customer(); customer.Name = name; customer.Number = number; customer.Tel = tel; return View(customer); } } }
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApplication1.Models;
namespace WebApplication1.Controllers { public class TestController : Controller { public IActionResult Index() { // 使用ViewData ViewData["Message"] = "Hello World!";
TestViewModel testViewModel = new TestViewModel(); testViewModel.Customer = new Customer() ; testViewModel.Customer.Name = "YU HSIANG"; testViewModel.Customer.Number = "A001"; testViewModel.Customer.Tel = "00-00000000";
testViewModel.Products = new List<Product>(); testViewModel.Products.Add(new Product() { Name = "PS4", Number = "P001", Price = 11000 }); testViewModel.Products.Add(new Product() { Name = "PS5", Number = "P002", Price = 15000 });
return View(testViewModel); } public JsonResult TestJsonResult() { return Json(new { data = 5 }); }
@model WebApplication1.Models.TestViewModel @* For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 *@ @ViewData["Message"]<br> @Model.Customer.Name<br> @Model.Customer.Number<br> @Model.Customer.Tel<br>
@model WebApplication1.Models.TestViewModel @* For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 *@ @ViewData["Message"]<br> @ViewBag.msg<br> @Model.Customer.Name <br> @Model.Customer.Number <br> @Model.Customer.Tel <br>
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using WebApplication1.Models;
namespace WebApplication1.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger;
public IActionResult Index() { // 透過Context取得資料 var model = _context.Customers.Select(b => new Customer { Name = b.Name, Number = b.Number, Tel = b.Tel }).ToList();
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks;
namespace WebApplication1.Models { public class UsersModel { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using WebApplication1.Models;
namespace WebApplication1.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) { _logger = logger; }
public IActionResult Index() { // 建立usersModel物件 UsersModel usersModel = new UsersModel() { ID = 1, Name = "YU HSIANG", Age = 25 }; // 傳入View return View(usersModel); }