如何使用OAuth 2.0实现REST API以实现多客户端访问

Mad*_*ita 1 c# sql-server membership-provider oauth-2.0 asp.net-web-api2

我有类似下面的要求使用OAuth 2.0和Web Api实现REST API.

REST API应该允许 - 创建,更新,查看和删除订单 - 来创建,更新,查看和删除库存

API应该能够被任何类型的外部客户端使用,例如Web应用程序,移动应用程序,Windows/Web服务等.

允许外部客户的角色:订单管理,库存管理外部客户的用户数据(角色,权限)将不由我们的系统管理.

注意:可以有另外两个角色,如内部,外部.因为外部用户不允许删除功能.

订单和库存数据将在当前Windows /桌面应用程序已使用的SQL Server DB中进行管理.通过新API发出的订单,库存应该保存在同一个数据库中.

问题:

  1. 我可以使用哪种授权类型?
  2. 我应该如何管理外部客户端的数据(允许的角色,客户端ID,令牌)?我需要为此使用单独的成员资格数据库吗?我可以将现有数据库用于新表吗?

Cha*_*mal 5

您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

并像这样授权你的API

[Authorize(Roles = "Developer")]
// GET: api/Tests
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}
Run Code Online (Sandbox Code Playgroud)

你可以像下面一样消费它,

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;
Run Code Online (Sandbox Code Playgroud)

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; }
}
Run Code Online (Sandbox Code Playgroud)

回答你的问题

  1. 您可以使用 client_credentials
  2. 在每个客户端的内部数据库中维护角色,内部OnGrantClientCredentials只按客户端ID获取角色并分配为声明.