使用自定义AuthorizeFilter ASP.NET Web API验证客户端应用程序

时间:2017-08-08 20:14:26

标签: c# asp.net asp.net-web-api asp.net-web-api2 identity

我可以使用

验证所有请求
  GlobalConfiguration.Configuration.Filters.Add(new Results.ClientAppAuthorization());

以下代码

            OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true

        };

我希望能够在继续请求令牌之前使用[ClientAppAuthorization]验证客户端应用

1 个答案:

答案 0 :(得分:1)

我认为您应该自定义OAuthAuthorizationServerProvider并覆盖ValidateClientAuthentication,然后在OAuthAuthorizationServerOptions中的Startup上使用它,如下所示:

public class CustomOAuthProvider : OAuthAuthorizationServerProvider
    {

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            //here Implement your Custom validation
            // check your validation conditions and if true call
            context.Validated();
            // and at end 
            return Task.FromResult<object>(null);
        }
    }

然后在启动时使用它

OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),

            //change here
            Provider = new CustomOAuthProvider(),
            //hange above line

            AuthorizeEndpointPath = new PathString("/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true

        };