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的依賴關係。 –