ASP.NET OAuth授权-使用ClientId和Secret与用户名和密码的区别

ASP.NET OAuth Authorization - Difference between using ClientId and Secret and Username and Password

我正在尝试在 ASP.NET WebAPI 2 中实现一个简单的 OAuthAuthorizationServerProvider。我的主要目的是学习如何获得移动应用程序的令牌。我希望用户使用用户名和密码登录,然后收到一个令牌(和一个刷新令牌,这样他们就不必在令牌过期后重新输入凭据)。稍后,我希望有机会打开 API 供其他应用程序外部使用(例如使用 Facebook api 等...)。

这是我设置授权服务器的方式:

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5),
    Provider = new SimpleAuthorizationServerProvider(new SimpleAuthorizationServerProviderOptions()
    {
        ValidateUserCredentialsFunction = ValidateUser
    }),
    RefreshTokenProvider = new SimpleRefreshTokenProvider()
});

这是我的 SimpleAuthorizationServerProviderOptions 实现:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public delegate Task<bool> ClientCredentialsValidationFunction(string clientid, string secret);
    public delegate Task<IEnumerable<Claim>> UserCredentialValidationFunction(string username, string password);
    public SimpleAuthorizationServerProviderOptions Options { get; private set; }

    public SimpleAuthorizationServerProvider(SimpleAuthorizationServerProviderOptions options)
    {
        if (options.ValidateUserCredentialsFunction == null)
        {
            throw new NullReferenceException("ValidateUserCredentialsFunction cannot be null");
        }
        Options = options;
    }

    public SimpleAuthorizationServerProvider(UserCredentialValidationFunction userCredentialValidationFunction)
    {
        Options = new SimpleAuthorizationServerProviderOptions()
        {
            ValidateUserCredentialsFunction = userCredentialValidationFunction
        };
    }

    public SimpleAuthorizationServerProvider(UserCredentialValidationFunction userCredentialValidationFunction, ClientCredentialsValidationFunction clientCredentialsValidationFunction)
    {
        Options = new SimpleAuthorizationServerProviderOptions()
        {
            ValidateUserCredentialsFunction = userCredentialValidationFunction,
            ValidateClientCredentialsFunction = clientCredentialsValidationFunction
        };
    }

    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        if (Options.ValidateClientCredentialsFunction != null)
        {
            string clientId, clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            var clientValidated = await Options.ValidateClientCredentialsFunction(clientId, clientSecret);
            if (!clientValidated)
            {
                context.Rejected();
                return;
            }
        }

        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        if (Options.ValidateUserCredentialsFunction == null)
        {
            throw new NullReferenceException("ValidateUserCredentialsFunction cannot be null");
        }

        var claims = await Options.ValidateUserCredentialsFunction(context.UserName, context.Password);
        if (claims == null)
        {
            context.Rejected();
            return;
        }

        // create identity
        var identity = new ClaimsIdentity(claims, context.Options.AuthenticationType);

        // create metadata to pass to refresh token provider
        var props = new AuthenticationProperties(new Dictionary<string, string>()
        {
            { "as:client_id", context.UserName }
        });

        var ticket = new AuthenticationTicket(identity, props);
        context.Validated(ticket);
    }

    public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
    {
        var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
        var currentClient = context.ClientId;

        // enforce client binding of refresh token
        if (originalClient != currentClient)
        {
            context.Rejected();
            return;
        }

        // chance to change authentication ticket for refresh token requests
        var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
        newIdentity.AddClaim(new Claim("newClaim", "refreshToken"));

        var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
        context.Validated(newTicket);
    }
}

我的 SimpleRefreshTokenProvider 实现:

public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
{
    private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens =
        new ConcurrentDictionary<string, AuthenticationTicket>(); 

    public void Create(AuthenticationTokenCreateContext context)
    {

    }

    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        var guid = Guid.NewGuid().ToString();

        var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
        {
            IssuedUtc = context.Ticket.Properties.IssuedUtc,
            ExpiresUtc = DateTime.UtcNow.AddYears(1)
        };
        var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

        _refreshTokens.TryAdd(guid, refreshTokenTicket);
        context.SetToken(guid);
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {

    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        AuthenticationTicket ticket;
        if (_refreshTokens.TryRemove(context.Token, out ticket))
        {
            context.SetTicket(ticket);
        }
    }
}

我不完全理解的是 ClientId and SecretUsername and Password 的用法。我粘贴的代码通过用户名和密码生成一个令牌,我可以使用该令牌(直到它过期),但是当我尝试获取刷新令牌时,我必须有 ClientId。

另外,如果令牌过期,正确的方法是发送刷新令牌并获取新令牌?如果刷新令牌被盗怎么办?这不就和用户名密码被盗一样吗?

What I don't fully understand is the use of ClientId and Secret vs Username and Password. The code I pasted generates a token by username and password and I can work with that token (until it expires), but when I try to get a refresh token, I must have the ClientId.

Also, if a token expires, the correct way is to send the refresh token and get a new token? What if the refresh token gets stolen? isn't it the same as a username & password getting stolen?

在 OAuth2 中,对于在协议定义的任何授权流程中对用户和客户端进行身份验证至关重要。客户端身份验证(正如您可能猜到的那样)强制仅由已知客户端使用您的 API。序列化的访问令牌一旦生成,就不会直接绑定到特定的客户端。请注意 ClientSecret 必须被视为机密信息,并且只能由能够以某种安全方式存储此信息的客户端(例如外部服务客户端,而不是 javascript 客户端)使用。

刷新令牌只是 OAuth2 的另一种“授权类型”,正如您正确指出的那样,它将替换用户的用户名和密码对。此令牌必须被视为机密数据(甚至比访问令牌更机密),但比在客户端存储用户名和密码更具优势:

  • 如果遭到破坏,用户可以将其撤销;
  • 它的生命周期有限(通常是几天或几周);
  • 它不会暴露用户凭据(攻击者只能获得发布刷新令牌的“范围”的访问令牌)。

我建议您在 official draft. I also recommend you this resource 中阅读有关 OAuth 2 中定义的不同授权类型的更多信息 我自己在 Web API 中首次实现 OAuth2 时发现它非常有用。

样品请求

这里有两个使用 fiddler 的请求示例,Resource Owner Password Credentials Grant:

Refresh Token Grant: