ASP.NET Identity Token Methods accepts all HTTP methods

时间:2017-11-13 06:49:07

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

I created pone webapi and implemented authentication. I have the token method to get the user token. All working fine.

Scenario: I tested the token method with the postman. Here I noted that I can use any type of HTTP method to request for the token. I think /token method should support POST method only. But when I use DELETE method also I got token. Same as, I can also use PUT, PATH etc.

Is this expected? I assume that it should return Method Not Supported other than POST requests.

1 个答案:

答案 0 :(得分: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);

        }
    }