你在那里发布的很好的资源。我也使用过它,并且我构建了一个完整的(Xamarin)可移植类库,该类库会在每个请求等时自动提交此令牌。
在 ASP.NET MVC 中,就像添加
[Authorize]
- 属性在您的 API 控制器上。如果您正确遵循指南,这将立即保护它们。
保护您的 API 后,您需要发送包含不记名令牌的请求。这就是我在项目中实现它的方式:
// First logging in and getting a token:
public async Task<bool> OAuthLoginAsync(string username, string password)
{
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
});
Token = await PostAndReadAsync<TokenResponse>(_oauthEndpointUri, formContent);
}
// this method is responsible for sending the request and returning an object
public async Task<T> PostAndReadAsync<T>(string path, HttpContent content)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
var responseMessage = await httpClient.PostAsync(path, content, cancellationToken);
if (!responseMessage.IsSuccessStatusCode) {
throw new Exception("Something went wrong...");
}
return await responseMessage.Content.ReadAsAsync<T>(cancellationToken);
}
}
代币定义:
public class TokenResponse
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty("as:client_id")]
public string ClientId { get; set; }
[JsonProperty("userName")]
public string UserName { get; set; }
[JsonProperty(".issued")]
public DateTime IssueDate { get; set; }
[JsonProperty(".expires")]
public DateTime ExpireDate { get; set; }
}
然后在任何后续的 api 调用中(你应该提供一个 oauth 令牌)你应该添加访问令牌。
HttpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Token.AccessToken);
作为一个额外的好处,前面指定的 PostAndReadAsync 方法可以重复使用来调用任何其他资源(当它返回时<T>
),因此它是可重复使用的。
我希望这会帮助你(以及许多其他面临同样问题的人)。如果这对您的情况不完整,请随时询问更多信息。
请注意,为简单起见,我删除了所有尝试/捕获和取消标记。
您的(共享)移动项目中需要以下 nuget 包:
Microsoft.Bcl
Microsoft.Bcl.Build
Microsoft.Bcl.Http
Microsoft.AspNet.WebApi.Client
Newtonsoft.Json