對應的應用場景是:為自家的網站開發手機 App(非第三方 App),只需用戶在 App 上登錄,無需用戶對 App 所能訪問的數據進行授權。
客戶端獲取Token:
public string GetAccessToken(string UserName, string UserPwd)
{
if (UserName == "xsj" && UserPwd == "123456")
{
HttpClient _httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri("http://localhost:61659");
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(UserName + ":" + UserPwd)));
var parameters = new Dictionary<string, string>();
parameters.Add("grant_type", "password");
parameters.Add("username", UserName);
parameters.Add("password", UserPwd);
string result = _httpClient.PostAsync("/Token", new FormUrlEncodedContent(parameters)).Result.Content.ReadAsStringAsync().Result;
}
return "";
}
基於 Owin OAuth, 針對 Resource Owner Password Credentials Grant 的授權方式,只需重載 OAuthAuthorizationServerProvider.GrantResourceOwnerCredentials() 方法即可。代碼如下:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//驗證context.UserName與context.Password //調用后台的登錄服務驗證用戶名與密碼
var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
var props = new AuthenticationProperties(new Dictionary<string, string> { { "client_id", context.ClientId } });
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
var ticket = new AuthenticationTicket(oAuthIdentity, props);
context.Validated(ticket);
await base.GrantResourceOwnerCredentials(context);
}
使用:
public string Call_WebAPI_By_Resource_Owner_Password_Credentials_Grant()
{
string token = await GetAccessToken("xsj", "123456");
if (token != "")
{
HttpClient _httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri("http://localhost:61659");
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return _httpClient.GetAsync("/UserInfo/GetCurrent")).Content.ReadAsStringAsync());
}
return "";
}
參考:http://www.cnblogs.com/dudu/tag/OAuth/
https://github.com/feiyit/MvcApiSecurity
