在這一部分中,我們將創(chuàng)建一個(gè)ASPNET核心項(xiàng)目,作為我們授權(quán)服務(wù)器的最低設(shè)置。我們將使用MVC來提供頁面,并將身份驗(yàn)證添加到項(xiàng)目中,包括一個(gè)基本的登錄表單。
創(chuàng)建一個(gè)空的asp.net core項(xiàng)目
正如前一篇文章中所說,授權(quán)服務(wù)器只是另一個(gè)web應(yīng)用程序。以下內(nèi)容將指導(dǎo)您使用用戶名密碼登錄來設(shè)置ASPNET Core應(yīng)用程序。我選擇不使用ASPNET core 標(biāo)識(shí)來保持簡單。基本上,每個(gè)用戶名密碼組合都可以工作。
讓我們從創(chuàng)建一個(gè)名為AuthorizationServer的新web應(yīng)用程序開始,使用 ASP.NET Core Empty template
dotnet new web --name AuthorizationServer
我們將只處理此項(xiàng)目,并且不會(huì)在本指南中添加解決方案文件。
OpenIddict要求我們使用https協(xié)議,即使在本地開發(fā)時(shí)也是如此。要確保本地證書是可信的,您必須運(yùn)行以下命令:
dotnet dev-certs https --trust
在Windows上,證書將被添加到證書存儲(chǔ)中,在OSX上,證書被添加到密鑰鏈中。在Linux上,沒有一種跨發(fā)行版的標(biāo)準(zhǔn)方式來信任證書。在Hanselman的博客文章中閱讀更多關(guān)于這個(gè)主題的信息。
啟動(dòng)應(yīng)用程序以查看是否一切正常
dotnet run --project AuthorizationServer
訪問localhost:5001應(yīng)該能看到Hello World!
mvc
我們已經(jīng)創(chuàng)建了一個(gè)基于ASPNET Core Empty模板的項(xiàng)目。這是一個(gè)非常小的模板。我這樣做是有意的,因?yàn)槲蚁矚g在我的項(xiàng)目中盡可能少的“噪音”,以保持事情的清晰和簡單。
使用這個(gè)模板的缺點(diǎn)是我們必須自己添加MVC。首先,我們需要通過更改Startup.cs類來啟用MVC:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.MapDefaultControllerRoute();
app.Run();
MVC是通過調(diào)用services.AddControllersWithViews()
。端點(diǎn)設(shè)置為使用默認(rèn)布線。我們還啟用了靜態(tài)文件的服務(wù),我們需要它來提供wwwroot文件夾中的樣式表。
現(xiàn)在,讓我們創(chuàng)建控制器、視圖和視圖模型。首先在項(xiàng)目文件夾中添加以下文件夾結(jié)構(gòu)(注意大小寫):
/Controllers
/Views
/Views/Home
/Views/Shared
/ViewModels
/wwwroot
/wwwroot/css
布局
我們添加的第一項(xiàng)是一個(gè)名為_layout.cshtml
的布局文件,該文件位于Views/Shared文件夾中。該文件定義了應(yīng)用程序的總體布局,還從CDN加載Bootstrap和jQuery。jQuery是Bootstrap的一個(gè)依賴項(xiàng)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no" />
<title>OpenIddict - Authorization Server</title>
@* <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" crossorigin="anonymous"> *@
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<div class="container-sm mt-3">
<div class="row mb-3">
<div class="col text-center">
<h1>
Authorization Server
</h1>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-8 col-xl-4 offset-md-2 offset-xl-4 text-center mb-3">
@RenderBody()
</div>
</div>
</div>
@* <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" crossorigin="anonymous"></script> *@
@* <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> *@
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.slim.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.bundle.min.js"></script>
</body>
</html>
為了使布局和視圖正常工作,我們需要將兩個(gè)文件添加到\views文件夾中:_ViewStart.cshtml
@{
Layout = "_Layout";
}
_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
首頁
在/Controllers文件夾中添加一個(gè)基本的HomeController,其唯一目的是為我們的主頁提供服務(wù):
將Index.chtml添加到Views/Home文件夾,該文件夾由HomeController提供服務(wù):
<h2>MVC is working</h2>
最后但同樣重要的是,我們需要一些造型。將名為site.css的樣式表添加到wwwroot\css文件夾中:
:focus {
outline: 0 !important;
}
.input-validation-error {
border: 1px solid darkred;
}
form {
width: 100%;
}
.form-control {
border: 0;
border-radius: 0;
border-bottom: 1px solid lightgray;
font-size: 0.9rem;
}
.form-control:focus {
border-bottom-color: lightgray;
box-shadow: none;
}
.form-control.form-control-last {
border-bottom: 0;
}
.form-control::placeholder {
opacity: 0.6;
}
.form-control.input-validation-error {
border: 1px solid darkred;
}
一些樣式規(guī)則已經(jīng)添加到樣式表中,預(yù)計(jì)我們稍后將創(chuàng)建登錄表單。
如果您想使用SASS,或使用SASS自定義引導(dǎo)程序,請(qǐng)查看我關(guān)于使用ASPNET設(shè)置引導(dǎo)程序SASS的文章。
讓我們運(yùn)行應(yīng)用程序,看看是否一切正常,您應(yīng)該在瀏覽器中看到這樣的內(nèi)容:
啟用身份驗(yàn)證
在ASP.NET Core,身份驗(yàn)證由IAuthenticationService處理。身份驗(yàn)證服務(wù)使用身份驗(yàn)證處理程序來完成與身份驗(yàn)證相關(guān)的操作。
身份驗(yàn)證處理程序在啟動(dòng)期間注冊(cè),其配置選項(xiàng)稱為“方案(scheme)”。身份驗(yàn)證方案是通過在“startup”中Startup.ConfigureServices
來指定的。
或者在這個(gè)項(xiàng)目中,我們將使用cookie身份驗(yàn)證,因此我們需要在Startup.cs的ConfigureServices方法中注冊(cè)cookie身份驗(yàn)證方案:
using Microsoft.AspNetCore.Authentication.Cookies;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/account/login";
});
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.MapDefaultControllerRoute();
app.Run();
登錄路徑設(shè)置為/account/login,我們將很快實(shí)現(xiàn)此端點(diǎn)。
通過調(diào)用應(yīng)用程序的 IApplicationBuilder 上的 UseAuthentication 擴(kuò)展方法來添加使用注冊(cè)的身份驗(yàn)證方案的身份驗(yàn)證中間件:
app.UseRouting();
app.UseAuthentication();//需要放在UseRouting和MapDefaultControllerRoute中間
app.MapDefaultControllerRoute();
對(duì) UseAuthentication 的調(diào)用是在調(diào)用 UseRouting 之后進(jìn)行的,以便路由信息可用于身份驗(yàn)證決策,但在 UseEndpoints 之前進(jìn)行,以便用戶在訪問端點(diǎn)之前進(jìn)行身份驗(yàn)證。
登錄頁面
現(xiàn)在我們已經(jīng)啟用了身份驗(yàn)證,我們將需要一個(gè)登錄頁面來驗(yàn)證用戶。
首先,創(chuàng)建包含我們驗(yàn)證用戶身份所需的信息的登錄視圖模型。 確保將此文件放入“ViewModels”文件夾中:
using System.ComponentModel.DataAnnotations;
namespace AuthorizationServer.ViewModels
{
public class LoginViewModel
{
[Required]
public string? Username { get; set; }
[Required]
public string? Password { get; set; }
public string? ReturnUrl { get; set; }
}
}
在“Views”文件夾中創(chuàng)建一個(gè)名為“Account”的文件夾,并添加登錄視圖“Login.cshtml”,其中包含登錄表單:
@model AuthorizationServer.ViewModels.LoginViewModel
<form autocomplete="off" asp-route="Login">
<input type="hidden" asp-for="ReturnUrl" />
<div class="card">
<input type="text" class="form-control form-control-lg" placeholder="Username" asp-for="Username" autofocus>
<input type="password" class="form-control form-control-lg form-control-last" placeholder="Password" asp-for="Password">
</div>
<p>
<button type="submit" class="btn btn-dark btn-block mt-3">Login</button>
</p>
</form>
最后,我們添加AccountController
using AuthorizationServer.ViewModels;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace AuthorizationServer.Controllers
{
public class AccountController : Controller
{
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model)
{
ViewData["ReturnUrl"] = model.ReturnUrl;
if (ModelState.IsValid)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.Username)
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity));
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction(nameof(HomeController.Index), "Home");
}
return View(model);
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
}
那么,這里會(huì)發(fā)生什么?我們?cè)趲艨刂破魃嫌袃蓚€(gè)登錄操作(GET 和 POST),都允許匿名請(qǐng)求,否則沒有人能夠登錄。
GET 操作為我們剛剛創(chuàng)建的登錄表單提供服務(wù)。 我們有一個(gè)可選的查詢參數(shù) returlUrl ,我們將其存儲(chǔ)在 ViewData 中,因此我們可以在成功登錄后使用它來重定向用戶。
POST 操作更有趣。 首先驗(yàn)證 ModelState。 這意味著需要用戶名和密碼。 我們?cè)谶@里不檢查憑據(jù),任何組合在此示例中都是有效的。 通常,您可以在此處根據(jù)數(shù)據(jù)庫檢查憑據(jù)。
當(dāng) ModelState 有效時(shí),將構(gòu)建聲明身份。 我們添加一項(xiàng)聲明,即用戶的姓名。 請(qǐng)注意,我們?cè)趧?chuàng)建聲明身份時(shí)指定了 cookie 身份驗(yàn)證方案 (CookieAuthenticationDefaults.AuthenticationScheme)。 這基本上是一個(gè)字符串,映射到我們?cè)谠O(shè)置 cookie 身份驗(yàn)證時(shí)在 Startup.cs 類中定義的身份驗(yàn)證方案。
SignInAsync方法是一個(gè)擴(kuò)展方法,它調(diào)用AuthenticationService,后者調(diào)用CookieAuthenticationHandler,因?yàn)檫@是我們?cè)趧?chuàng)建聲明標(biāo)識(shí)時(shí)指定的方案。
登錄后我們需要重定向用戶。 如果指定了返回 url,我們會(huì)在重定向之前檢查它是否是本地 url,以防止開放重定向攻擊。 否則,用戶將被重定向到主頁。
最后一個(gè)操作Logout調(diào)用身份驗(yàn)證服務(wù)以注銷用戶。身份驗(yàn)證服務(wù)將調(diào)用身份驗(yàn)證中間件,在我們的例子中是cookie身份驗(yàn)證中間件來注銷用戶。
更新首頁
更新主頁(Views/Home/Index.cshtml)
@using Microsoft.AspNetCore.Authentication
@if (User?.Identity?.IsAuthenticated == true)
{
var authenticationResult = await Context.AuthenticateAsync();
var issued = authenticationResult?.Properties?.Items[".issued"];
var expires = authenticationResult?.Properties?.Items[".expires"];
<div>
<p>You are signed in as</p>
<h2>@User.Identity.Name</h2>
<hr />
<dl>
<dt>Issued</dt>
<dd>@issued</dd>
<dt>Expires</dt>
<dd>@expires</dd>
</dl>
<hr />
<p><a class="btn btn-dark" asp-controller="Account" asp-action="Logout">Sign out</a></p>
</div>
}
@if (User?.Identity?.IsAuthenticated != true)
{
<div>
<p>You are not signed in</p>
<p><a class="btn btn-sm btn-dark" asp-controller="Account" asp-action="Login">Sign in</a></p>
</div>
}
如果用戶已通過身份驗(yàn)證,我們將顯示用戶名、當(dāng)前會(huì)話信息和注銷按鈕。當(dāng)用戶未通過身份驗(yàn)證時(shí),我們會(huì)顯示一個(gè)登錄按鈕,用于將用戶導(dǎo)航到登錄表單。
賬號(hào)密碼隨便輸入即可
退出就會(huì)回到登錄頁面文章來源:http://www.zghlxwxcb.cn/news/detail-799598.html
目前,我們有一個(gè)基本的ASPNET核心項(xiàng)目在運(yùn)行,并實(shí)現(xiàn)了身份驗(yàn)證,到目前為止還沒有什么新奇之處。接下來,我們將把OpenIddict添加到項(xiàng)目中,并實(shí)現(xiàn)客戶端憑據(jù)流。文章來源地址http://www.zghlxwxcb.cn/news/detail-799598.html
到了這里,關(guān)于通過OpenIddict設(shè)計(jì)一個(gè)授權(quán)服務(wù)器02-創(chuàng)建asp.net項(xiàng)目的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!