没有身份验证Asp.net核心的Cookie [英] Cookie without Identity Asp.net core

查看:97
本文介绍了没有身份验证Asp.net核心的Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一个不使用Identity的项目.

I'm currently working on a project that I don't use Identity.

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

The things is that this project should have a remember me option that allow user to automatically reconnect into the web site.

我的问题是,如果没有Identity,我找不到任何完整的指导老师来创建Cookie.

My problem is that I can't find any complete tutoriel to create a cookie without Identity.

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

If somebody have a good sample of code or tutoial :)

谢谢

推荐答案

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

In my project, I use AngularJS for Frontend and .Net Core API for Backend. So, I don't need to configure pages for AccessDeniedPath, LoginPath and so on.

这就是我要做的:

  • 在启动类中配置cookie:

  • Configure the cookie in the startup class:

public void Configure(IApplicationBuilder app) {
  //...
  CookieAuthenticationOptions options = new CookieAuthenticationOptions();
  options.AuthenticationScheme = "MyCookie";
  options.AutomaticAuthenticate = true;
  options.CookieName = "MyCookie";
  app.UseCookieAuthentication(options);
  //...
}

  • 登录名是这样的:

  • The login is like this:

    [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();
    }
    

  • 注销如下:

  • The logout is like this:

    [HttpPost, Route("Logout")]
    public async Task<IActionResult> LogOut() {
      await HttpContext.Authentication.SignOutAsync("MyCookie");
      return Ok();
    }
    

  • 然后您可以像这样使用它:

  • Then you can use it like this:

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

  • *请注意,该方法仅被授权用于角色1,角色2和角色3".并查看如何获取用户名.

    *See that the method is authorized only for "Role1, Role2 and Role3". And see how to get the user name.

    这篇关于没有身份验证Asp.net核心的Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆