Reputation: 315
I am able to receive the token with Postman but the code gives me an error:
@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
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:
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);
}
Upvotes: 1
Views: 233
Reputation: 342
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)));
}
Upvotes: 1