编程语言
首页 > 编程语言> > c#-使用OAuthAuthorizationServer自定义允许的授予类型

c#-使用OAuthAuthorizationServer自定义允许的授予类型

作者:互联网

我正在为Web API实现OAuth 2.0.最初,我要允许的唯一授权类型是“资源所有者密码授权类型”的“密码”.将来,我可能会扩展到其他股票赠款类型,甚至建立自定义股票赠款类型.为了实现,我在Startup.cs类中创建了以下代码.我没有指定授权端点,而只是指定令牌端点.

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }

    public void ConfigureAuth(IAppBuilder app)
    {

        var myOAuthServerProvider = new MyOAuthServerProvider();

        app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {

            // mark true if you are not on https channel. This should never be true for Production.
            AllowInsecureHttp = true,

            //Enable a 60 minute expiration time.
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),

            // Allows the authorization server to alter the response coming out so it can report a 401.
            AuthenticationMode = AuthenticationMode.Active,

            // Provider needs to be the custom class that performs our authentication. 
            Provider = myOAuthServerProvider,

            // This specifies the endpoint path where you can generate a token. 
            TokenEndpointPath = new PathString("/api/token"),

        });
    }
}

对于MyOAuthServerProvider类,我应该继承自OAuthAuthorizationServerProvider并重写特定方法以仅允许要启用的授予类型,还是应该从头开始从IOAuthAuthorizationServerProvider接口实现MyOAuthServerProvider?

解决方法:

要仅允许您希望从OAuthAuthorizationServerProvider继承的授权类型就足够了.然后,您需要重写两个方法:

> ValidateClientAuthentication-验证请求的来源是已注册的client_id
> GrantResourceOwnerCredentials-在grant_type设置为password时验证提供的用户名和密码

有关更多信息,请参见GrantResourceOwnerCredentials方法的文档:

Called when a request to the Token endpoint arrives with a “grant_type” of
“password”. This occurs when the user has provided name and password credentials
directly into the client application’s user interface, and the client application
is using those to acquire an “access_token” and optional “refresh_token”.
If the web application supports the resource owner credentials grant type
it must validate the context.Username and context.Password as appropriate.
To issue an access token the context.Validated must be called with a new
ticket containing the claims about the resource owner which should be associated
with the access token. The application should take appropriate measures to
ensure that the endpoint isn’t abused by malicious callers. The default
behavior is to reject this grant type.

标签:asp-net-web-api2,oauth-2-0,c
来源: https://codeday.me/bug/20191119/2038326.html