C# ASP.NET核心中基于声明的授权

C# ASP.NET核心中基于声明的授权,c#,.net,authorization,asp.net-core-mvc,claims-based-identity,C#,.net,Authorization,Asp.net Core Mvc,Claims Based Identity,是否有一个权威的示例项目使用ASP.NET Core基于声明的授权 类似于[对于MVC.一小时的研讨会可以吗 请注意,这并不是说基于声明,因为这不再特别。ASP.NET Core中的所有标识(现在是Core,而不是vNext)是索赔身份。根据我的个人经验,对索赔的正确解释以及如何真正使用索赔几乎没有什么。因此,我将通过一个示例来分享我的解释。它使用Visual Studio 2015中创建的默认ASP.NET MVC核心项目 这里需要记住的是,用户可以有一个或多个声明。他可以声明自己是“管理员

是否有一个权威的示例项目使用ASP.NET Core基于声明的授权


类似于[对于MVC.

一小时的研讨会可以吗


请注意,这并不是说基于声明,因为这不再特别。ASP.NET Core中的所有标识(现在是Core,而不是vNext)是索赔身份。

根据我的个人经验,对索赔的正确解释以及如何真正使用索赔几乎没有什么。因此,我将通过一个示例来分享我的解释。它使用Visual Studio 2015中创建的默认ASP.NET MVC核心项目

这里需要记住的是,用户可以有一个或多个声明。他可以声明自己是“管理员”,并且“名称”等于“bhail”因此,他们使用索赔这个词。有趣的是,索赔可以由ASP.Net应用程序分配,甚至可以从Facebook、Twitter等其他来源分配。这一点非常重要,因为我们开始使用SPA和移动应用程序,这些应用程序使用代币,反过来嵌入索赔。但这是另一天。 在下面的示例中,我修改了默认的AccountController,以便在用户注册时将多个索赔分配给用户:

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {

                await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(ClaimTypes.Role, "Admin"));
                await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(ClaimTypes.Name, "Bhail"));
                await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(ClaimTypes.DateOfBirth, "18/01/1970"));
                await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(ClaimTypes.Country, "UK"));



                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation(3, "User created a new account with password.");

                return RedirectToLocal(returnUrl);
            }
            AddErrors(result);
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

好了!基本上,策略是声明的集合。根据策略进行检查。声明本身被分配给用户。与角色分配不同,您现在拥有从各种来源进行多对多授权的权力和灵活性。

这非常有帮助。为控制器应用策略的能力是什么ew/仅限于ASP.NET Core…或者在MVC5中也有这样做的方法吗?Core中的新功能。MSFT之外的一些人正在尝试将其移植回,但我不知道这是如何进行的。好的。MSFT之外的人是否有公开的正在进行的项目?
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        // Adjustment to params from the default settings
        services.AddIdentity<ApplicationUser, ApplicationRole>()
      .AddEntityFrameworkStores<ApplicationDbContext, int>()
      .AddDefaultTokenProviders();


        services.AddMvc();

        #region Configure all Claims Policies

        services.AddAuthorization(options =>
        {
            //options.AddPolicy("Administrators", policy => policy.RequireRole("Admin"));
            options.AddPolicy("Administrators", policy => policy.RequireClaim(ClaimTypes.Role, "Admin")); // This works the same as the above code
            options.AddPolicy("Name", policy => policy.RequireClaim(ClaimTypes.Name, "Bhail"));

        });
        #endregion

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }
    [Authorize(Policy = "Administrators")]
    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        return View();
    }

    [Authorize(Policy = "Name")]
    public IActionResult Contact()
    {
        ViewData["Message"] = "Your contact page.";

        return View();
    }

    public IActionResult Error()
    {
        return View();
    }
}