没有身份Asp.net核心的Cookie

时间:2016-12-02 15:38:31

标签: c# asp.net-core

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

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

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

如果某人有一个很好的代码或tutoial样本:)

谢谢

3 个答案:

答案 0 :(得分:3)

在我的项目中,我使用AngularJS作为Frontend和.Net Core API for Backend。 因此,我不需要为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;
      //...
    }
    

*请参阅该方法仅被授权用于&#34; Role1,Role2和Role3&#34;。并了解如何获取用户名。

答案 1 :(得分:1)

我认为你问的是当用户使用&#34;记住我时,如何制作持久性cookie?&#34;选中复选框。

所有答案都在正确的路径上 - 您最终会调用Arrays.stream(array) .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())) .entrySet() .forEach(e -> System.out.println(e.getValue() + "\t" + e.getKey() + (e.getValue() > 1 ? "s" : ""))); ,但Cookie中间件默认会发出会话Cookie。您需要将身份验证属性作为第三个参数传递,以使Cookie持久,例如:

HttpContext.Authentication.SignInAsync

答案 2 :(得分:0)

这里有一篇非常好的文章:Using Cookie Middleware without ASP.NET Core Identity

基本上你所做的就是设置cookie处理中间件,好像你要识别用户,但是你只需要创建一个ClaimsPrincipal对象而不要求用户登录。您将该对象传递给SigninAsync方法,它会为您创建cookie。如果你遵循这篇文章,你应该没事。

相关问题