代码之家  ›  专栏  ›  技术社区  ›  Shan Khan

Angular 4 Http请求提供错误取消支持授予类型,使用web API Owin Jwt令牌

  •  1
  • Shan Khan  · 技术社区  · 7 年前

    enter image description here

    错误的请求400,不支持的\u Grant\u类型

    let option: RequestOptions = new RequestOptions();
        option.headers = new Headers();
        option.headers.append("Content-Type", "application/x-www-form-urlencoded");
        //option.headers.append('access-control-allow-origin','*');
    
        option.body = JSON.parse(JSON.stringify({ username: username, password: password, grant_type: 'password' }));
        option.method = RequestMethod.Post;
       return  this.http.request("http://localhost:4200/oauth/token", option).map((response: Response) => {
            // login successful if there's a jwt token in the response
            let user = response.json();
            if (user && user.token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
            } 
        });
    

    通过使用Post请求,这是代码:

     let option: RequestOptions = new RequestOptions();
        option.headers = new Headers();
        option.headers.append("Content-Type", "application/x-www-form-urlencoded");
        option.method = RequestMethod.Post;
       return this.http.post('/oauth/token', JSON.stringify({ username: username, password: password, grant_type: "password" }), option)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let user = response.json();
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }
            });
    

    enter image description here

     POST /oauth/token HTTP/1.1
    Host: localhost:4200
    Connection: keep-alive
    Content-Length: 65
    Accept: application/json, text/plain, */*
    Origin: http://localhost:4200
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
    Content-Type: application/x-www-form-urlencoded
    Referer: http://localhost:4200/login?returnUrl=%2Fhome
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.8
    

    {"username":"shan","password":"ShanAli!","grant_type":"password"}
    

    我的WEB应用程序位于端口4200上

    以下是C#的详细信息:

    public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            ConfigureOAuthTokenGeneration(app);
            ConfigureOAuthTokenConsumption(app);
    
            // ASPNETCORE_ENVIRONMENT should be set to 'Development'
            if (env != null && env.IsDevelopment())
            {
                app.UseErrorPage(ErrorPageOptions.ShowAll);
            }
    
            var config = new HttpConfiguration();
            ConfigureWebApi(config);
            // Swagger
            SwaggerConfig.Register(config);
            // Register routes
            WebApiConfig.Register(config);
    
            var builder = new ContainerBuilder();
    
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    
            // Run other optional steps, like registering filters,
            // per-controller-type services, etc., then set the dependency resolver
            // to be Autofac.
            var erpAssembly = Assembly.Load(ConfigurationManager.AppSettings["ErpAdapter"]);
    
            builder.RegisterAssemblyModules(erpAssembly);
            builder.RegisterType<ErpAdapterFactory>().As<IErpAdapterFactory>().InstancePerRequest();
    
            var container = builder.Build();
            var diResolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = diResolver;
    
            // OWIN WEB API SETUP:
    
            // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
            // and finally the standard Web API middleware.
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
    
            app.UseWebApi(config);
    
    
        }
        private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                //For Dev enviroment only (on production should be AllowInsecureHttp = false)
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/oauth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat("http://localhost:40909")
            };
    
            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
        }
    
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
    
            var issuer = "http://localhost:40909";
            string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
            byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);
    
            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { audienceId },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                    }
                });
        }
    
        private void ConfigureWebApi(HttpConfiguration config)
        {
           // config.MapHttpAttributeRoutes();
    
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Andrei Dragotoniu    7 年前

    在您的JavaScript代码中,我没有看到您在哪里设置授权基本头。

    同样在您的后端代码中,我没有看到您查看请求并实际检查正确的AudienceID和传递的秘密的部分。

    CustomOAuthProviderclass中有什么?

    https://eidand.com/2015/03/28/authorization-system-with-owin-web-api-json-web-tokens/

    它应该能回答您的所有问题,只要您用JavaScript正确构建请求,一切都会正常工作。

    我另外要注意的是,要非常小心地允许不安全的http。你不想把它设置为true。所有内容都应该通过https,因为这样你的标题和帖子正文就会被加密。否则他们将被曝光,任何人基本上都可以窃取你的id和机密,然后继续发行有效令牌。所以,一路使用https。