Tez*_*eld 5 c# asp.net-web-api2
如果我直接进入它,我已经构建了一个RESTful服务(WebAPIV2)basic authentication......一切都按预期工作,但我非常不确定如何从ClaimsPrincipal. 我读过很多文章,但都指向使用第三方库和/或Identity在.Net.
为了保持简短和甜蜜,我有一个Attribute执行必要的逻辑和一个authenticateService指向我的data store.
我有一个n-tier architecture:
所以我想第一个问题是,我如何从中读取值ClaimsPrincipal?(抱歉第一次使用 Claims)
注意:我希望每次请求都会触发这个,不会有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;
}
}
Run Code Online (Sandbox Code Playgroud)
在 my 中访问声明值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.");
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢您花时间阅读本文,希望“有人”可以指导/帮助我阅读声明值和/或传递层的最佳方法。
问候,
小智 10
您可以通过这种方式访问声明。在您的控制器方法中:
try
{
// ...
var claimsIdentity = (ClaimsIdentity)this.RequestContext.Principal.Identity;
foreach(var claim in claimsIdentity.Claims)
{
// claim.value;
// claim.Type
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
小智 7
@User.Claims.FirstOrDefault(c => c.Type == "Currency").Value
Run Code Online (Sandbox Code Playgroud)