[英]Unable to get a token from different Angular project url on a cors enabled .net API
I am able to receive the token with postman but the code gives me an error:我可以使用 postman 接收令牌,但代码给了我一个错误:
@Injectable()
export class AuthService {
constructor(private http: HttpClient) {
}
login(username: string, password: string) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
formData.append('grant_type', 'password');
return this.http.post<any>(`${environment.apiUrl}token`, formData, httpOptions)
.pipe(map(user => this.setSession(user)));
}
private setSession(authResult) {
const expiresAt = moment().add(authResult.expiresIn, 'second');
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()));
}
}
My headers:我的标题:
:authority: localhost:44302:method: POST:path: /api/token:scheme: https accept: application/json, text/plain, / accept-encoding: gzip, deflate, br accept-language: en-US,en;q=0.9 content-length: 372 content-type: application/x-www-form-urlencoded origin: https://localhost:44354 referer: https://localhost:44354/login sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: same-site user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36
:authority: localhost:44302:method: POST:path: /api/token:scheme: https accept: application/json, text/plain, / accept-encoding: gzip, deflate, br accept-language: en-US,en ;q=0.9 内容长度:372 内容类型:应用程序/x-www-form-urlencoded 来源: https://localhost:44354引用者: https://localhost:44354/login sec-fetch-dest:空-fetch-mode: cors sec-fetch-site: same-site user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36
My Error:我的错误:
ERROR
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "https://localhost:44302/api/token", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 400
statusText: "OK"
url: "https://localhost:44302/api/token"
ok: false
name: "HttpErrorResponse"
message: "Http failure response for https://localhost:44302/api/token: 400 OK"
error: {error: "unsupported_grant_type"}
__proto__: HttpResponseBase
API Token section: API 令牌部分:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
LogoutPath = new PathString("/Account/LogOff"),
ExpireTimeSpan = TimeSpan.FromMinutes(5.0),
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/API/Token"),
Provider = new OAuthAppProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
AllowInsecureHttp = true //Don't do this in production ONLY FOR DEVELOPING: ALLOW INSECURE HTTP!
};
app.UseOAuthBearerTokens(OAuthOptions);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
Try this:尝试这个:
login(username: string, password: string) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
const formData = 'grant_type=password&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password);
return this.http.post<any>(`${environment.apiUrl}token`, formData, httpOptions)
.pipe(map(user => this.setSession(user)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.