从ClaimsPrincipal检索/读取索赔值

时间:2017-02-28 10:24:08

标签: c# asp.net-web-api2

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

为了保持简短和甜蜜,我有一个Attribute表示必要的逻辑和一个指向authenticateService的自定义data store

我有n-tier architecture

  1. API
  2. 服务
  3. 商业
  4. 数据
  5. 所以我想第一个问题是,如何从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.");
            }
        }
    

    非常感谢您花时间阅读本文,希望“某人”可以指导/帮助我阅读声明值和/或传递图层的最佳方法。

    此致

4 个答案:

答案 0 :(得分:3)

@User.Claims.FirstOrDefault(c => c.Type == "Currency").Value

答案 1 :(得分:2)

您可以通过这种方式访问​​声明。在您的控制器方法中:

RaisedPropertyChanged

答案 2 :(得分:0)

答案 3 :(得分:0)

用于查看 Azure Functions 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 + "\n\n" + claims + "\n\n" + claimDetail);
}