Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Send OAuth2 POST request with Angular 6 , with the correct headers?

I need to send a post request to a Spring Boot OAuth 2 Authorization Server to aquire the JWT token ? Using Postman I got the token and the Auth Server is working OK. But With Angular I am having a hard time figuring out the correct post request format?

This is the current method I'm using.

login() {
  const url = 'http://localhost:9090/oauth/token';

  const data = {
    'grant_type': 'password',
    'username': 'username',
    'password': 'password'
  };

  const reqH = new HttpHeaders({
    'Content-Type': 'application/x-www-urlencoded',
    'Authorization': 'Basic ' + btoa('client-id' + ':' + 'secret'),
    'grant_type': 'password',
    'username': 'administrator%40divinedragon.com',
    'password': 'password'
  });

  return this.http.post('http://localhost:9090/oauth/token', data, {
    headers: reqH
  });
}

when using this method I get the following error.

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "http://localhost:9090/oauth/token", ok: false, …},

error: {error: "invalid_request", error_description: "Missing grant type"}

Help is greatly appreciated !

like image 211
rashm1n Avatar asked Aug 31 '25 17:08

rashm1n


1 Answers

I think you are putting username and password in header and body as well. it worked for me as below:

login(username, password) {
    const headers = {
        'Authorization': 'Basic ' + btoa('devglan-client:$2a$04$e/c1/RfsWuThaWFCrcCuJeoyvwCV0URN/6Pn9ZFlrtIWaU/vj/BfG'),
        'Content-type': 'application/x-www-form-urlencoded'
    }

    const body = new HttpParams()
        .set('username', username)
        .set('password', password)
        .set('grant_type', 'password');

    this.http.post('http://localhost:8080/' + 'oauth/token', body, {headers})
        .subscribe(data => this.setToken(data),
            err => alert('invalid Creadtilas'));
}
like image 105
Shardendu Avatar answered Sep 02 '25 06:09

Shardendu