欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

asp.net core MVC之實現(xiàn)基于token的認證

 更新時間:2021年05月07日 14:08:03   作者:CN_Simo  
這篇文章主要介紹了asp.net core MVC之實現(xiàn)基于token的認證,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

安裝Nuget包

項目中添加包:dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

添加認證配置

Startup類中添加如下配置:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    }); 
}

AddAuthentication方法會向依賴注入容器添加認證服務(wù)和它所使用的其他服務(wù),其參數(shù)defaultScheme用于指定當未指定具體的認證方案時將會使用的默認方案,上例為Bearer認證。

AddAuthentication方法的另一重載能夠使用AuthenticationOptions類為認證過程中的每一個動作指明所使用的認證方案,如DefaultAuthenticateScheme、
DefaultChallengeScheme、
DefaultSignInScheme、
DefaultSignOutScheme、
DefaultForbidScheme。
如果沒有為這些屬性設(shè)置認證方案,則將使用DefaultScheme屬性所指定的值。

當添加JwtBearer認證方式時,JwtBearerOptions對象能夠配置該認證的選項,它的TokenValidationParameters屬性用于指定驗證Token時的規(guī)則:

var tokenSection = Configuration.GetSection("Security:Token");
services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => {
    options.TokenValidationParameters = new TokenValidationParameters{
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuer = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = tokenSection["Issuer"],
        ValidAudience = tokenSection["Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(tokenSection["Key"])
        ),
        ClockSkew = TimeSpan.Zero
    };
});

TokenValidationParameters類作為Token驗證參數(shù)類,它包含了一些屬性,這些屬性如ValidateAudience、ValidateIssuer、ValidateLifetime和ValidateIssuerSigningKey,它們都是布爾類型,用于指明是否驗證相應(yīng)的項;而ValidIssuer和ValidAudience屬性則用于指明合法的簽發(fā)者(Issuer)與接受方(Audience)。在上例中,它們的值都從配置文件中獲取;IssuerSigningKey屬性的值用于指定進行簽名驗證的安全密鑰,它的值為SymmetricSecurityKey對象,即對稱加密密鑰;ClockSkew屬性的值表示驗證時間的時間偏移值。

上述代碼會從配置文件中讀取關(guān)于Token的信息,因此還需在appsettings.json中添加如下內(nèi)容。

"Security": {
  "Token": {
    "Issuer": "demo_issuer",
    "Audience": "demo_audience",
    "Key": "<your_secret_key>"
  }
}

為Controller添加認證

接下來,為了使用ASP.NET Core的認證功能來保護資源,應(yīng)為Controller或Action添加[Authorize]特性,該特性能夠?qū)崿F(xiàn)在訪問相應(yīng)的Controller或Action時,要求請求方提供指定的認證方式,它位于Microsoft.AspNetCore.Authorization命名空間中。需要為AuthorController和BookController添加該特性。

[Authorize]
public class AuthorController : ControllerBase
{
}
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class BookController : ControllerBase
{
}

如果使用了多個認證方式,則可以使用[Authorize]特性的AuthenticationSchemes屬性指明當前Controller或Action要使用哪一種認證方式(如上例中的BookController);如果不設(shè)置,則會使用所添加認證時設(shè)置的默認方案;如果沒有設(shè)置默認方案,則會出現(xiàn)InvalidOperationException異常,并提示未指定默認方案;此外,如果為AuthenticationSchemes屬性指定了不存在的方案名稱,也會出現(xiàn)InvalidOperationException異常。

此時再訪問Book和Author資源,會出現(xiàn)401 Unauthorized異常:

如果要允許某個Action可以被匿名訪問,可以在Action方法上添加屬性標記 [AllowAnonymous]:

[AllowAnonymous]
public async Task<ActionResult<IEnumerable<AuthorDto>>> GetAuthorsAsync([FromQuery] AuthorResourceParameters parameters)

添加認證信息生成接口

JwtBearer中間件提供了對JWT的驗證功能,然而并未提供生成Token的功能。要生成Token,可以使用JwtSecurityTokenHandler類,它位于System.IdentityModel.Tokens.Jwt命名空間,它不僅能夠生成JWT,由于它實現(xiàn)了ISecurityTokenValidator接口,因此對JWT的驗證也是由它完成的。接下來,我們將創(chuàng)建一個Controller,它將會根據(jù)用戶的認證信息生成JWT,并返回給客戶端。

在Controllers文件夾中創(chuàng)建一個Controller,名為AuthenticateController,內(nèi)容如下:

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace Library.Api.Controllers
{
    [ApiController, Route("api/auth")]
    public class AuthenticateController : ControllerBase
    {
        public IConfiguration Configuration { get; }
        public AuthenticateController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        [HttpPost("token", Name = nameof(GenerateToken))]
        public IActionResult GenerateToken(string username, string password)
        {
            if (username != "demouser" || password != "demopassword")
            {
                return Unauthorized();
            }

            var claims = new List<Claim>{
                new Claim(JwtRegisteredClaimNames.Sub, username)
            };

            var tokenConfigSection = Configuration.GetSection("Security:Token");
            var key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(tokenConfigSection["Key"])
            );
            var signCredential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(
                issuer: tokenConfigSection["Issuer"],
                audience: tokenConfigSection["Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(3),
                signingCredentials: signCredential
            );

            return Ok(new {
                token = new JwtSecurityTokenHandler().WriteToken(jwtToken),
                expiration = TimeZoneInfo.ConvertTimeFromUtc(jwtToken.ValidTo, TimeZoneInfo.Local)
            });
        }
    }
}

在AuthenticateController中的GenerateToken方法中,通過創(chuàng)建JwtSecurityToken對象,并使用JwtSecurityTokenHandler對象的WriteToken方法最終得到生成的JWT。當創(chuàng)建JwtSecurityToken對象時,我們可以指定issuer、audience以及當前用戶的Claim信息,此外,還可以指定該Token的有效時間。這里需要注意,由于JWT不支持銷毀以及撤回功能,因此在設(shè)置它的有效時間時,應(yīng)設(shè)置一個較短的時間(如上例中的3分鐘),這樣可以有效避免Token在意外被竊取后所帶來的風險。

現(xiàn)在就可以請求認證接口獲取 token:

這時重新請求資源接口,在請求頭中添加Authorization項,值為Bearer ,就可以得到結(jié)果了:

這次示例中,使用了固定的用戶名和密碼,實際情況中,用戶名和密碼通常是存在數(shù)據(jù)庫中的,可以使用ASP.NET Core Identity來實現(xiàn)這一功能。

到此這篇關(guān)于asp.net core MVC之實現(xiàn)基于token的認證的文章就介紹到這了,更多相關(guān)asp.net core token的認證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論