我有如下要求,以使用OAuth 2.0和Web Api实现REST API。
REST API应该允许-创建,更新,查看和删除订单-创建,更新,查看和删除库存
任何类型的外部客户端(例如Web应用程序,移动应用程序,Windows / Web服务等)都应该能够使用API。
外部客户允许的角色:订单管理,库存管理我们的系统将不管理外部客户的用户数据(角色,权限)。
注意:可以有另外两个角色,例如Internal,External。因为外部用户不允许使用删除功能。
订单和库存数据将在当前Windows /桌面应用程序已经使用的SQL Server数据库中进行管理。通过新的API发出的订单,库存应保存在同一数据库中。
问题:
您可以使用Microsoft.Owin.Security.OAuth
提供程序。请看下面的示例。
创建新的OwinStartup
文件并按Configuration
以下方法更改方法
public void Configuration(IAppBuilder app)
{
var oauthProvider = new OAuthAuthorizationServerProvider
{
OnGrantClientCredentials = async context =>
{
var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
// based on clientId get roles and add claims
claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Developer"));
claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Developer2"));
context.Validated(claimsIdentity);
},
OnValidateClientAuthentication = async context =>
{
string clientId;
string clientSecret;
// use context.TryGetBasicCredentials in case of passing values in header
if (context.TryGetFormCredentials(out clientId, out clientSecret))
{
if (clientId == "clientId" && clientSecret == "secretKey")
{
context.Validated(clientId);
}
}
}
};
var oauthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/accesstoken"),
Provider = oauthProvider,
AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(3),
SystemClock = new SystemClock()
};
app.UseOAuthAuthorizationServer(oauthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
}
并像这样授权您的API
[Authorize(Roles = "Developer")]
// GET: api/Tests
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
您可以像下面那样食用它,
string baseAddress = "http://localhost/";
var client = new HttpClient();
// you can pass the values in Authorization header or as form data
//var authorizationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes("clientId:secretKey"));
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationHeader);
var form = new Dictionary<string, string>
{
{"grant_type", "client_credentials"},
{"client_id", "clientId"},
{"client_secret", "secretKey"},
};
var tokenResponse = client.PostAsync(baseAddress + "accesstoken", new FormUrlEncodedContent(form)).Result;
var token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
var authorizedResponse = client.GetAsync(baseAddress + "/api/Tests").Result;
令牌.cs
internal class Token
{
[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; }
}
您问题的答案
client_credentials
OnGrantClientCredentials
只需按客户ID获取角色并分配为声明即可。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句