參考文獻(xiàn):
http://www.js-code.com/xindejiqiao/xindejiqiao_274882.html
https://www.cnblogs.com/xiaoxiaotank/p/15811749.html
編寫代碼過程中不理解的代碼可參考上面的文獻(xiàn)
首先需要配置你的Program.cs,代碼如下:
//在ASP.NET Core應(yīng)用程序中配置依賴注入容器,將 HttpContextAccessor 注冊為一個(gè)服務(wù)
builder.Services.AddHttpContextAccessor();
//選擇使用那種方式來身份驗(yàn)證(Cookie)
builder.Services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; //默認(rèn)身份驗(yàn)證方案Cookie
option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
option.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;
option.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option =>
{
option.LoginPath = "/Login/AdminLoginView";//如果沒有找到用戶信息---身份驗(yàn)證失敗--授權(quán)也失敗了---就跳轉(zhuǎn)到指定的Action
option.AccessDeniedPath = "/Login/AdminLoginView";//訪問被拒絕就跳轉(zhuǎn)到指定的Action
});
然后開啟中間件
// 身份認(rèn)證中間件
app.UseAuthentication();
app.UseAuthorization();
?創(chuàng)建一個(gè)AuthenticationMiddleware.cs類
private readonly RequestDelegate _next;
public AuthenticationMiddleware(RequestDelegate next, IAuthenticationSchemeProvider schemes)
{
_next = next;
Schemes = schemes;
}
public IAuthenticationSchemeProvider Schemes { get; set; }
public async Task Invoke(HttpContext context)
{
// 記錄原始路徑和原始基路徑
context.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
{
OriginalPath = context.Request.Path,
OriginalPathBase = context.Request.PathBase
});
// 如果有顯式指定的身份認(rèn)證方案,優(yōu)先處理(這里不用看,直接看下面)
var handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
{
var handler = await handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
if (handler != null && await handler.HandleRequestAsync())
{
return;
}
}
// 使用默認(rèn)的身份認(rèn)證方案進(jìn)行認(rèn)證,并賦值 HttpContext.User
var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticate != null)
{
var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
if (result?.Principal != null)
{
context.User = result.Principal;
}
}
await _next(context);
}
在寫登錄的地方去使用
/// <summary>
/// 用戶登錄
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task<ResultDto<int>> AdminLogin(LoginDto dto)
{
try
{
var model = await _adminRepository.FindAsync(a => a.AdminAccount == dto.LoginName);
if (model.AdminAccount == null)
{
return new ResultDto<int>
{
code = 0,
data = 2,
msg = "用戶不存在",
};
}
bool isCode = Validate2(dto.Id, dto.ValidateCode);
if (!isCode)
{
return new ResultDto<int>
{
code = 0,
data = 3,
msg = "驗(yàn)證碼錯(cuò)誤"
};
}
if (model.AdminPassword.ToUpper() == dto.LoginPassword.Md5().ToUpper())
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaims(new[]
{
new Claim(ClaimTypes.NameIdentifier,model.AdminId.ToString()),//存儲登錄的角色的AdminId
new Claim(ClaimTypes.Name,model.AdminName),//存儲登錄的角色的AdminName
});
var principal = new ClaimsPrincipal(identity);
// 登錄設(shè)置項(xiàng) 比如過期時(shí)間
var properties = new AuthenticationProperties
{
ExpiresUtc = DateTimeOffset.UtcNow.AddSeconds(60),
AllowRefresh = true
};
await _httpcontext.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
return new ResultDto<int>
{
code = 0,
data = 1,
msg = "登陸成功"
};
}
else
{
return new ResultDto<int>
{
code = 0,
data = 4,
msg = "密碼錯(cuò)誤"
};
}
}
catch (Exception)
{
throw;
}
}
?最后給你的控制器加上[Authorize]特性就可以了。文章來源:http://www.zghlxwxcb.cn/news/detail-605155.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-605155.html
到了這里,關(guān)于Asp.Net Core 6 Cookie 的身份驗(yàn)證策略的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!