rashm1n
rashm1n

Reputation: 85

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 !

Upvotes: 4

Views: 8657

Answers (3)

Touqeer Aslam
Touqeer Aslam

Reputation: 220

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

Upvotes: 0

UI_Dev
UI_Dev

Reputation: 200

var body = "grant_type=password&username=username&password=password&client_id=clientid";
    
return this.http.post(`${this.oauth.URL}/oauth/token`, body, {
    headers: new HttpHeaders({
    Authorization: "Basic +token",
    "Content-type": "application/x-www-form-urlencoded;charset=utf-8"
    })
});

Upvotes: 0

Shardendu
Shardendu

Reputation: 3590

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'));
}

Upvotes: 9

Related Questions