400 Bad Request przy autoryzacji (ASP .NET)

0

Czesc jestem nowy w swiecie i jak zwykle w nowej technologii roznie sie autoryzacja, niby banal ale najwiecej czasu sie na to traci wiec potrzebuje pomocy za dlugo juz to probuje zrobic. Kumaci beda wiedzieli o co chodzi. O to kodzik.

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            ConfigureOAuth(app);

            WebApiConfig.Register(config);

            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            var myProvider = new AuthorizationProvider();
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };

            app.UseOAuthAuthorizationServer(options);
        }
    }

public class AuthorizationProvider : OAuthAuthorizationServerProvider
    {
        private UserService UserService = null;

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override Task MatchEndpoint(OAuthMatchEndpointContext context)
        {
            if (context.IsTokenEndpoint && context.Request.Method == "OPTIONS")
            {

                if (!context.OwinContext.Response.Headers.Keys.Contains("Access-Control-Allow-Origin"))
                    context.OwinContext.Response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Origin", new[] { ConfigurationManager.AppSettings["allowedOrigin"] });

                if (!context.OwinContext.Response.Headers.Keys.Contains("Access-Control-Allow-Headers"))
                    context.OwinContext.Response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", new[] { "Accept", "Content-Type", "Authorization", "Cache-Control", "Pragma", "Origin" });
                if (!context.OwinContext.Response.Headers.Keys.Contains("Access-Control-Allow-Methods"))
                    context.OwinContext.Response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", new[] { "GET", "POST", "PUT", "DELETE", "OPTIONS" });
                context.MatchesTokenEndpoint();
                context.RequestCompleted();
                return Task.FromResult<object>(null);
            }

            return base.MatchEndpoint(context);
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            var allowedOrigin = "*";

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

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            UserService = new UserService(new UserRepository(new App()));

            var IdentityUser = UserService.IdentityUser(context.UserName, context.Password);

            if (IdentityUser != null)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                identity.AddClaim(new Claim("login", IdentityUser.login));
                identity.AddClaim(new Claim("username", IdentityUser.nickname));
                identity.AddClaim(new Claim(ClaimTypes.Name, IdentityUser.name));
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
    }

Front

        $http.post('http://localhost:53112/token', data)
          .then(({ data }) => {
              deferred.resolve(data);
          }).catch((err) => {
            deferred.reject(err);
          });

Najpierw mialem problem z OPTIONS ale dzieki m.in app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); ten blad zniknal niestety pojawia sie teraz problem przy samym POST. W odpowiedzi dostaje 400 na twarz z unsupported grant type, mimo ze jest wprowadzony. Rece opadaja,

0

A, chcialbym jeszcze dodac ze request na Postman dziala, a jak robie request przez angulara to jest blad.

1 użytkowników online, w tym zalogowanych: 0, gości: 1