您可以使用Microsoft.Owin.Security.OAuth 提供程序。请查看以下示例。
新建 Owin Startup 文件并更改 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;
Token.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 获取角色并分配为声明。