參考文獻: http://www.js-code.com/xindejiqiao/xindejiqiao_274882.html https://www.cnblogs.com/xiaoxiaotank/p/15811749.html 編寫代碼過程中不理解的代碼可參考上面的文獻 首先需要配置你的Pr ...
參考文獻:
http://www.js-code.com/xindejiqiao/xindejiqiao_274882.html
https://www.cnblogs.com/xiaoxiaotank/p/15811749.html
編寫代碼過程中不理解的代碼可參考上面的文獻
首先需要配置你的Program.cs,代碼如下:
//在ASP.NET Core應用程式中配置依賴註入容器,將 HttpContextAccessor 註冊為一個服務
builder.Services.AddHttpContextAccessor();
//選擇使用那種方式來身份驗證(Cookie)
builder.Services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; //預設身份驗證方案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";//如果沒有找到用戶信息---身份驗證失敗--授權也失敗了---就跳轉到指定的Action
option.AccessDeniedPath = "/Login/AdminLoginView";//訪問被拒絕就跳轉到指定的Action
});
然後開啟中間件
// 身份認證中間件
app.UseAuthentication();
app.UseAuthorization();
創建一個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
});
// 如果有顯式指定的身份認證方案,優先處理(這裡不用看,直接看下麵)
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;
}
}
// 使用預設的身份認證方案進行認證,並賦值 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 = "驗證碼錯誤"
};
}
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);
// 登錄設置項 比如過期時間
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 = "密碼錯誤"
};
}
}
catch (Exception)
{
throw;
}
}
最後給你的控制器加上[Authorize]特性就可以了。