从索赔中检索/读取索赔价值



如果我直接进入它,我已经使用basic authentication构建了RESTful服务(WebAPI V2)...一切都按预期工作,但是我不确定如何检索值来自ClaimsPrincipal。我已经阅读了许多文章,但所有这些都指向.Net中使用第三方库和/或Identity

要保持简短而甜美,我有一个Attribute执行必要的逻辑和一个指向我的data store的自定义authenticateService

我有一个n-tier architecture

  1. api
  2. 服务
  3. 业务
  4. 数据

所以我想第一个问题是,如何读取ClaimsPrincipal中的值?(对第一次使用索赔道歉)

要注意:我希望每个请求都会开火,没有session

一些创建和身份验证用户的逻辑(内部Attribute

using (var authService = new AuthenticateService())
            {
                var client = await _authenticateService.AuthenticateAsync(
                    apiKey,
                    password);
                if (client != null)
                {
                    // Create a ClaimsIdentity with all the claims for this user.
                    Claim apiKeyClaim = new Claim("API Key", apiKey);
                    Claim clientNameClaim = new Claim(ClaimTypes.Name, client.ClientName);
                    Claim clientKeyClaim = new Claim("Client Key", client.ClientKey);
                    List<Claim> claims = new List<Claim>
                    {
                        apiKeyClaim,
                        clientNameClaim,
                        clientKeyClaim
                    };
                    // important to set the identity this way, otherwise IsAuthenticated will be false
                    // see: http://leastprivilege.com/2012/09/24/claimsidentity-isauthenticated-and-authenticationtype-in-net-4-5/
                    ClaimsIdentity identity = new ClaimsIdentity(claims, "Basic");
                    // AuthenticationTypes.Basic
                    var principal = new ClaimsPrincipal(identity);
                    return principal;
                    //var principal = new GenericPrincipal(new GenericIdentity("CustomIdentification"),
                    //                   new[] { "SystemUser" });
                    //return principal;
                }
                else
                {
                    return null;
                }
            }

在我的API controller中访问索赔值:

[IdentityBasicAuthentication]
    [Authorize]
    [RoutePrefix("api")]
    public class OrderController : ApiController
    {
        private IOrderService _orderService;
        public OrderController(IOrderService orderService)
        {
            _orderService = orderService;
        }
        // POST api/<controller>
        [HttpPost]
        [Route("order")]
        public async Task<IHttpActionResult> Post([FromBody]Models.Model.Order order)
        {
            var modelResponse = new ModelResponse<Models.Model.Order>(order);
            if (order == null)
                return BadRequest("Unusable resource.");
            if (!modelResponse.IsModelValid())
                return this.PropertiesRequired(modelResponse.ModelErrors());
            try
            {
                //Create abstracted Identity model to pass around layers
                // Access Claim values here
                //OR can I use Claims in other layers without creating an abstracted model to pass through.
                await _orderService.AddAsync(order);
            }
            catch (System.Exception ex)
            {
                return InternalServerError();
            }
            finally
            {
                _orderService.Dispose();
            }
            return Ok("Order Successfully Processed.");
        }
    }

非常感谢您阅读这篇文章的时间,希望"某人"可以指导/帮助我阅读索赔价值观和/或最佳方法。

问:

您可以以这种方式访问索赔。在您的控制器方法中:

try 
{
    // ...
    var claimsIdentity = (ClaimsIdentity)this.RequestContext.Principal.Identity;
    foreach(var claim in claimsIdentity.Claims)
    {
        // claim.value;
        // claim.Type
    }
    // ...
}
@User.Claims.FirstOrDefault(c => c.Type == "Currency").Value

对于那些想知道如何从.net7 aspcore中获得主题ID的人,可以像

一样轻松地完成。
var claim = principal.FindFirst(Claims.Subject); 
var id = Guid.Parse(claim?.Value ?? ""); // or cast/parse it to the expected type

我更喜欢linq而不是访问可以在这里找到:https://msdn.microsoft.com/en-us/library/ee517271.aspx?f=255&amp; mspperror = 2147217396

可用于查看所有权限&amp;Azure函数v3(NetCore3.1)中的索赔。从各种SO文章中一起散发。

...
using System.Security.Claims;
using System.Linq;
...
[FunctionName("AdminOnly")]
public static async Task<IActionResult> RunAdminOnly(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "test")] HttpRequest req,
ILogger log,
ClaimsPrincipal claimsID)
{
    string perms ="";
    foreach(var h in req.Headers)
    {
        perms += $"{h.Key}:{String.Join(",", h.Value)}" + "n";
    }
    string claims = "";
    foreach (Claim claim in claimsID.Claims)
    {
        claims += $"{claim.Type} : {claim.Value} n";
    }
    string claimDetail = "";
    Claim? appRole = claimsID.Claims.FirstOrDefault(c => c.Type == "extension_AppRole"); // custom claim
    claimDetail += appRole?.Value.ToString();
    return new OkObjectResult(perms + "nn" + claims + "nn" + claimDetail);
}

最新更新