ASP.NET Identity Token Methods接受所有HTTP方法

Akh*_*hil 6 c# asp.net-web-api asp.net-identity

我创建了pap webapi并实现了身份验证.我有令牌方法来获取用户令牌.一切正常.

场景: 我用邮递员测试了令牌方法.在这里,我注意到我可以使用任何类型的HTTP方法来请求令牌.我认为/ token方法应该只支持POST方法.但是当我使用DELETE方法时,我也得到了令牌.同样,我也可以使用PUT,PATH等.

这是预期的吗?我假设除了POST请求之外它应该返回Method Not Supported.

Saa*_*adi 2

您可以编写自定义 OAuthAuthorizationServerOptions.Provider。并使用上下文仅接受 Http Post 请求

OAuthAuthorizationServerOptions 是 asp.net 身份核心类。您可以在此命名空间 Microsoft.Owin.Security.OAuth 下找到它。

示例代码:

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

        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }

    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            if (context.Request.Method != "POST")
            {
                context.SetError("invalid_request", "Invalid request");
                return;
            }

            using (AuthRepository _repo = new AuthRepository())
            {
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
    }
Run Code Online (Sandbox Code Playgroud)