[英]RESTful service basic authentication
我只是在本教程的基礎上構建了一個RESTful服務作為練習。 因此,它基本上是一個在Visual Studio 2013中創建的Web API項目。
我已經對其進行了修改,以便它將返回包含一些地址的JSON字符串。 我還編寫了一個小型客戶端應用程序,該應用程序基本上只讀取該字符串並將地址顯示在屏幕上。
創建項目時,我使用“單個用戶帳戶”檢查了“身份”。 因此,我有可用的ApplicationOAuthProvider。
從這里開始,盡管我有點迷茫。 我發現很多教程都使用某種自我實現的基本身份驗證。 但是我想盡可能地靠近模板項目,直到我完全了解自己在做什么。
我請求數據的控件如下所示:
public IHttpActionResult Get()
{
return Json(db.vwAdressen);
}
使用[Authorize]過濾器,我(當然)會收到一條未經授權的錯誤消息,盡管我不知道這是否是我正確實現身份驗證所需的全部。 並且,當然,發送帶有憑據的請求。
用於通過BasicAuthentication保護我的api。 我發現使用Thinktecture.IdentityModel.Owin.Basic Authentication
庫是最容易實現的庫。
從這里獲取這個nuget包
現在,在您的owin
Startup
類中,在configure方法中編寫以下語句-
public void Configuration(IAppBuilder app)
{
app.UseBasicAuthentication("MyAppAuthRealm", ValidateUser);
...
}
...其中ValidateUser
是實際上將使用基本身份驗證來驗證用戶的方法。
然后實現類似這樣的ValidateUser
方法-( 為簡單起見,我假設用戶名和密碼對於有效用戶是相等的。您擁有驗證用戶的邏輯 )-
private Task<IEnumerable<System.Security.Claims.Claim>> ValidateUser(string id, string secret)
{
if (id == secret)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, id),
new Claim(ClaimTypes.Role, "Foo")
};
return Task.FromResult<IEnumerable<Claim>>(claims);
}
return Task.FromResult<IEnumerable<Claim>>(null);
}
現在再次在您的Configuration
方法中,在注冊Web api配置之前使用以下語句-
app.UseClaimsTransformation(TransformClaims);
其中, TransformClaims
是將聲明轉換為應用程序標識的方法。
private Task<ClaimsPrincipal> TransformClaims(ClaimsPrincipal incoming)
{
if (!incoming.Identity.IsAuthenticated)
{
return Task.FromResult<ClaimsPrincipal>(incoming);
}
// parse incoming claims - create new principal with app claims
var claims = new List<Claim>
{
new Claim(ClaimTypes.Role, "foo"),
new Claim(ClaimTypes.Role, "bar")
};
var nameId = incoming.FindFirst(ClaimTypes.NameIdentifier);
if (nameId != null)
{
claims.Add(nameId);
}
var thumbprint = incoming.FindFirst(ClaimTypes.Thumbprint);
if (thumbprint != null)
{
claims.Add(thumbprint);
}
var id = new ClaimsIdentity("Application");
id.AddClaims(claims);
return Task.FromResult<ClaimsPrincipal>(new ClaimsPrincipal(id));
}
現在,您可以像這樣從客戶端調用您的api-
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(
X509.CurrentUser
.My
.SubjectDistinguishedName
.Find("CN=client")
.First());
var client = new HttpClient(handler)
{
BaseAddress = new Uri("https://myWebApp/api/")
};
client.SetBasicAuthentication("foo", "foo");
var result = client.GetStringAsync("requestUri").Result;
您可以從所有者那里找到示例以獲取更多詳細信息-https: //github.com/IdentityModel/Thinktecture.IdentityModel/tree/master/samples/OWIN/AuthenticationTansformation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.