错误的请求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));
}
});
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();
}