身份驗證是這樣一個過程:由用戶提供憑據,然后將其與存儲在操作系統、數據庫、應用或資源中的憑據進行比較。?在授權過程中,如果憑據匹配,則用戶身份驗證成功,可執行已向其授權的操作。?授權指判斷允許用戶執行的操作的過程。也可以將身份驗證理解為進入空間(例如服務器、數據庫、應用或資源)的一種方式,而授權是用戶可以對該空間(服務器、數據庫或應用)內的哪些對象執行哪些操作。
微軟官方文檔
asp.net core支持多種授權,本篇重點說明JWT的基于角色授權方式。
基于JWT角色身份驗證和授權,思路是在登錄時分發加密的Token,在訪問資源時帶有這個Token,服務端要驗證這個Token是不是自己分發的,如果是,再驗證訪問范圍是否正確,本篇的范圍就是那些資源是那種角色訪問,得到Token的用戶當前是那種角色,也就是角色和資源的匹配。
用asp.net core實現步驟:
1、appsettings.json中配置JWT參
2、添加身份認證和授權服務和中間件
3、定義生成Token的方法和驗證Toekn參數的方法
4、登錄時驗證身份并分發Toekn
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;var builder = WebApplication.CreateBuilder();
//獲取JWT參數,并注入到服務容器
var jwtConfig = new JWTConfig();
builder.Configuration.GetSection("JWTConfig").Bind(jwtConfig);
builder.Services.AddSingleton(jwtConfig);
//添加JJWT方式的身份認證和授權,
builder.Services.AddAuthorization().AddAuthentication(options =>{options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opt =>{opt.RequireHttpsMetadata = false;opt.TokenValidationParameters = JwtToken.CreateTokenValidationParameters(jwtConfig);});var app = builder.Build();
//使用身份認證和授權的中間件
app.UseAuthentication();
app.UseAuthorization();app.MapGet("/hellosystem", (ILogger<Program> logger, HttpContext context) =>
{var message = $"hello,system,{context.User?.Identity?.Name}";logger.LogInformation(message);return message;
}).RequireAuthorization(new RoleData { Roles = "system" });app.MapGet("/helloadmin", (ILogger<Program> logger, HttpContext context) =>
{var message = $"hello,admin,{context.User?.Identity?.Name}";logger.LogInformation(message);return message;
}).RequireAuthorization(new RoleData { Roles = "admin" });app.MapGet("/helloall", (ILogger<Program> logger, HttpContext context) =>
{var message = $"hello,all roles,{context.User?.Identity?.Name}";logger.LogInformation(message);return message;
}).RequireAuthorization(new RoleData { Roles = "admin,system" });//登錄成功,并分發Token
app.MapPost("/login", [AllowAnonymous] (ILogger<Program> logger, LoginModel login, JWTConfig jwtConfig) =>
{logger.LogInformation("login");if (login.UserName == "gsw" && login.Password == "111111"){var?now?=?DateTime.UtcNow;var claims = new Claim[] {new Claim(ClaimTypes.Role, "admin"),new Claim(ClaimTypes.Name, "桂素偉"),new Claim(ClaimTypes.Sid, login.UserName),new Claim(ClaimTypes.Expiration, now.AddSeconds(jwtConfig.Expires).ToString())};var token = JwtToken.BuildJwtToken(claims, jwtConfig);return token;}else{return "username or password is error";}
});app.Run();
//登錄實體
public class LoginModel
{public string? UserName { get; set; }public string? Password { get; set; }
}
//JWT配置
public class JWTConfig
{public string? Secret { get; set; }public string? Issuer { get; set; }public string? Audience { get; set; }public int Expires { get; set; }
}
//JWT操作類型
public class JwtToken
{//獲取Tokenpublic static dynamic BuildJwtToken(Claim[] claims, JWTConfig jwtConfig){var now = DateTime.UtcNow;var jwt = new JwtSecurityToken(issuer: jwtConfig.Issuer,audience: jwtConfig.Audience,claims: claims,notBefore: now,expires: now.AddSeconds(jwtConfig.Expires),signingCredentials: GetSigningCredentials(jwtConfig));var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);var response = new{Status = true,AccessToken = encodedJwt,ExpiresIn = now.AddSeconds(jwtConfig.Expires),TokenType = "Bearer"};return response;}static SigningCredentials GetSigningCredentials(JWTConfig jwtConfig){var keyByteArray = Encoding.ASCII.GetBytes(jwtConfig?.Secret!);var signingKey = new SymmetricSecurityKey(keyByteArray);return new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);}//驗證Token的參數public static TokenValidationParameters CreateTokenValidationParameters(JWTConfig jwtConfig){var keyByteArray = Encoding.ASCII.GetBytes(jwtConfig?.Secret!);var signingKey = new SymmetricSecurityKey(keyByteArray);return new TokenValidationParameters{ValidateIssuerSigningKey = true,IssuerSigningKey = signingKey,ValidateIssuer = true,ValidIssuer = jwtConfig?.Issuer,ValidateAudience = true,ValidAudience = jwtConfig?.Audience,ClockSkew = TimeSpan.Zero,RequireExpirationTime = true,};}
}
//mini?api添加驗證授權的參數類型
public class RoleData : IAuthorizeData
{public string? Policy { get; set; }public string? Roles { get; set; }public string? AuthenticationSchemes { get; set; }
}
驗證結果:
1、沒有登錄,返回401
2、登錄,取token
3、正確訪問
4、沒有授權訪問,返回403
總結
以上是生活随笔為你收集整理的.NET6之MiniAPI(九):基于角色的身份验证和授权的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。