1、设置登录的路径
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/Login/Index";
options.LogoutPath = "/Login/Logout";
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
});
2、新建一个BaseController控制器继承自Controller代码如下:
namespace aaa
{
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public class BaseController : Controller
{
//此处是做各种操作的拦截
}
}
namespace aaaa
{
public class HomeController : BaseController
{
public IActionResult Index()
{
return View();
}
}
}
3、以上设置就会首次访问登录LoginController控制器了,为了登录成功之后下次直接进入home控制器需要在LoginController中如下设置:
/// <summary>
/// 登陆成功
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
[HttpPost]
public ActionResult SubmitLogin(JObject json)//前端用json进行交互
{
var result = JsonConvert.DeserializeObject<IDictionary<string, string>>
(json.ToString());
AjaxResult res = userService.SubmitLogin(result["username"], result["password"]);
string Token = "123456";
string Name = result["username"];
ClaimsIdentity identity = new ClaimsIdentity("Forms");
identity.AddClaim(new Claim(ClaimTypes.Sid, Token));
identity.AddClaim(new Claim(ClaimTypes.Name,Name));
ClaimsPrincipal claims = new ClaimsPrincipal(identity);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,claims);
return Content(res.ToJson());
}