c# - 没有身份的 Cookie Asp.net core

标签 c# asp.net-core

我目前正在开发一个不使用 Identity 的项目。

问题是这个项目应该有一个记住我的选项,允许用户自动重新连接到网站。

我的问题是我找不到任何完整的教程来创建没有身份的 cookie。

如果有人有很好的代码示例或教程:)

谢谢

最佳答案

在我的项目中,我使用 AngularJS 作为前端,使用 .Net Core API 作为后端。 因此,我不需要为 AccessDeniedPathLoginPath 等配置页面。

这就是我所做的:

  • 在启动类中配置cookie:

    public void Configure(IApplicationBuilder app) {
      //...
      CookieAuthenticationOptions options = new CookieAuthenticationOptions();
      options.AuthenticationScheme = "MyCookie";
      options.AutomaticAuthenticate = true;
      options.CookieName = "MyCookie";
      app.UseCookieAuthentication(options);
      //...
    }
    
  • 登录是这样的:

    [HttpPost, Route("Login")]
    public IActionResult LogIn([FromBody]LoginModel login) {
      //...
      var identity = new ClaimsIdentity("MyCookie");
      //add the login as the name of the user
      identity.AddClaim(new Claim(ClaimTypes.Name, login.Login));
      //add a list of roles
      foreach (Role r in someList.Roles) {
        identity.AddClaim(new Claim(ClaimTypes.Role, r.Name));
      }
      var principal = new ClaimsPrincipal(identity);
      HttpContext.Authentication.SignInAsync("MyCookie", principal).Wait();
      return Ok();
    }
    
  • 注销是这样的:

    [HttpPost, Route("Logout")]
    public async Task<IActionResult> LogOut() {
      await HttpContext.Authentication.SignOutAsync("MyCookie");
      return Ok();
    }
    
  • 然后你可以像这样使用它:

    [HttpPost]
    [Authorize(Roles = "Role1,Role2,Role3")]
    public IActionResult Post() {
      //...
      string userName = this.User.Identity.Name;
      //...
    }
    

*请注意该方法仅被授权给“Role1、Role2 和 Role3”。并查看如何获取用户名。

关于c# - 没有身份的 Cookie Asp.net core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935872/

相关文章:

c# - 从 NameValueCollection 中删除单个值

C# 等待和处理任务

c# - 将它们移动到另一个类后如何重命名属性或公共(public)字段?

c# 在 chrome 中使用哈希 (#) 打开 url

c# - 如何使用 .NET 的 string.Join 方法在值为 null 时打印自定义字符串?

c# - ASP.NET Core - Swashbuckle 未创建 swagger.json 文件

c# - 无法连接到网络服务器 'IIS Express'

asp.net-mvc - 在Asp.Net Core中上传图片?

javascript - 使用 Ajax 在完整日历上显示数据而不显示记录

asp.net-core - 如何将健康检查端点添加到 ApiExplorer,以便 Swashbuck 将其包含在生成的 swagger.json 中