I am trying to login using tokens in Angular. For this I need to send the username and password through the POST method including header and parameter.
These are the header and parameters:
'Content-Type','application/x-www-form-urlencoded'
'scope','...lo que sea...'
'grant_type', 'password'
'Authorization','... lo que sea...'
But I don't know how to include this data in the POST so that it returns the access_token and the other fields.
I have tried the following:
let cabecera = new HttpHeaders();
let parametros = new HttpParams();
cabecera.set('Content-Type','application/x-www-form-urlencoded').set('Authorization','...');
parametros.set('grant_type', 'password');
parametros.set('scope','...');
let opciones = {
headers: cabecera,
params: parametros
}
this.http.post(this.url,opciones).subscribe(data =>{
console.log(data);
})
But the username and password will not be added in this way for verification. And it returns errors.
I solved it this way:
I had to add the username and password inside the parameters as well.
Hello, it seems to me that you are passing the parameters to the POST wrong, I show you an example of a POST:
The method
post
accepts 3 arguments,URL
which is the destination HTTP address,OBJ
which is the json to send as the body of the request, and the 3rd parameter isOPTIONS
, which you can use to send the headers you need, just like in the example above. ( https://angular.io/guide/http#making-a-post-request )One thing that is important to know about Angular and its way of handling requests is that
HttpHeaders
and objectsHttpParams
are immutable . Every time you use the methodset(...)
, you have to save the returned object.An example request might look like this:
Explanation:
A common way of sending the username and password is basic authentication , which requires passing the string
'Basic <usuario>:<password>'
in the header to Base64"Authorization"
. The server's response can vary, from sending only the token or sending it with more information in a JSON or other format. The problem is that passing to base 64 special characters can be a source of problems, so in the given example certain previous transformations are performed, that's why I added theb64EncodeUnicode
.