0
如果我直接了解它,我已经构建了RESTful
服务(WebAPI
V2)和basic authentication
...所有工作都按预期工作,但我很不确定如何从ClaimsPrincipal
。我读过很多文章,但都指向使用第三方库和/或Identity
的.Net
。从索赔中检索/读取索赔值主要
为了保持它的简短和甜美,我有一个Attribute
执行必要的逻辑和一个自定义authenticateService
它指向我的data store
。
我有一个n-tier architecture
:
- API
- 服务
- 业务
- 数据
所以我想第一个问题是,如何从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.");
}
}
真的很欣赏你的时间读这篇文章,希望 “有人” 可以直接/帮助我阅读理赔值和/或传递层次的最佳方法。
Regards,
为了公平起见,我使用了与此非常相似的东西。我想在几个小时和几个小时后,我的脑子都死了,尽管我还添加了一个自定义对象来传递我的类库,但不添加对Claims和Identity的依赖关系。 –