I am trying to invoke an Authorization Token API to get an access token. The trigger is from an angular application via a button click.
The angular service code is below:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from './../auth/user';
import { AuthResponse } from './../auth/auth-response';
import { tap } from 'rxjs/operators';
import { Observable, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
AUTH_SERVER = "http://localhost:3000";
authSubject = new BehaviorSubject(false);
constructor(private httpClient: HttpClient) { }
register(user: User): Observable<AuthResponse> {
return this.httpClient.post<AuthResponse>(`${this.AUTH_SERVER}/register`, user).pipe(
tap((res: AuthResponse ) => {
if (res.token) {
console.log("ACCESS_TOKEN : "+ res.token.access_token);
localStorage.set("ACCESS_TOKEN", res.token.access_token);
localStorage.set("EXPIRES_IN", res.token.token_type);
localStorage.set("ACCESS_TOKEN", res.token.expires_in);
localStorage.set("EXPIRES_IN", res.token.refresh_token);
this.authSubject.next(true);
}
})
);
}
}
And the NodeJS Backend service code is below:
const express = require('express')
const https = require('https')
const app = express()
const router = express.Router();
const cors = require('cors');
const bodyParser = require("body-parser")
const api_helper = require('./util/api_helper')
const port = 3000
app.use(cors());
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
router.get('/', (req, res) => {
res.status(200).send('Welcome to Make REST API Calls to Authorisation Server In Express!');
});
router.post('/register', (req, res) => {
console.log('nodejs user name = '+req.body.username);
console.log('nodejs password = '+req.body.password);
var client_id = 'xxxx';
var client_secret = 'yyyyyy';
var auth_header = 'Basic ' + Buffer.from(client_id + ':' + client_secret).toString('base64');
const data = "grant_type=password&username=ddddd&password=eeeeee&client_id=fff&client_secret=Joe75";
const options = {
hostname: 'linux-2222',
port: 8543,
path: '/xxxx/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-formurlencoded',
'Content-Length': data.length
}
};
const requestVar = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
requestVar.write(data);
requestVar.end();
req.on('error', (error) => {
console.log('error is ' + error);
});
});
app.use(router);
app.listen(port, () => console.log(`Node server listening on port ${port}!`))
The error I am getting is below:
Entering the server endpoint
nodejs user name = xxx
nodejs password = yyyy
(node:6285) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
**TypeError: req.write is not a function**
at /Users/admin/Development/mod/integrator/src/app/app.js:78:7
at invokeCallback (/Users/admin/Development/mod/integrator/node_modules/raw-body/index.js:224:16)
events.js:288
throw er; // Unhandled 'error' event
^
Error: socket hang up
at connResetException (internal/errors.js:604:14)
at TLSSocket.socketOnEnd (_http_client.js:460:23)
at TLSSocket.emit (events.js:323:22)
at endReadableNT (_stream_readable.js:1204:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketOnEnd (_http_client.js:460:9)
at TLSSocket.emit (events.js:323:22)
at endReadableNT (_stream_readable.js:1204:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ECONNRESET'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! integrator@0.0.1 start: `NODE_TLS_REJECT_UNAUTHORIZED='0' node ./src/app/contractor_lifecycle_app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the integrator@0.0.1 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/admin/.npm/_logs/2020-03-28T11_37_38_559Z-debug.log
The nodejs console shows errors with : TypeError: req.write is not a function and Error: socket hang up . FYI, I am getting the access token in postname using the relevant http request options. And I was able to use the access token to get a protected resource in postman.
But, I cannot even consume the authorization endpoint via nodejs express.
Please, I need someone to help, any ideas will do. It appears the problem is with the https.request logic, but I dont know exactly where.
NOTE: The request parameter from the angular app is being successfuly logged in the console in the nodejs https request post function.
The req in the following line:
router.post('/register', (req, res) => {
was overriding the following:
req.write(data);
req.end();
The request write()
and end()
are methods of the object returned from https.request(options, (res) => {
So, I have updated the code by assigning the https.request(options, (res) => {
.. to a new varibale called requestVar.
And now I am getting my acccess token from the authorization server. I have updated original post with the fix. Hurray.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.