@c8y/client
Version:
Client application programming interface to access the Cumulocity IoT-Platform REST services.
67 lines • 2.41 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MicroserviceClientRequestAuth = void 0;
/**
* Allows to use either Cookie-Auth or Basic-Auth
* of a microservice client request header
* for Authorization to the Cumulocity API.
*/
class MicroserviceClientRequestAuth {
/**
* Authenticates using the credentials which were
* provided within the request headers of the
* client call to the microservice.
* @param headers
*/
constructor(headers = {}) {
this.xsrfToken = this.getCookieValue(headers, 'XSRF-TOKEN');
this.authTokenFromCookie = this.getCookieValue(headers, 'authorization');
this.authTokenFromHeader = headers.authorization;
}
updateCredentials() {
return undefined;
}
getFetchOptions(options) {
const headers = {
Authorization: this.authTokenFromCookie
? `Bearer ${this.authTokenFromCookie}`
: this.authTokenFromHeader,
...(this.xsrfToken ? { 'X-XSRF-TOKEN': this.xsrfToken } : undefined)
};
options.headers = Object.assign(headers, options.headers);
return options;
}
getCometdHandshake(config = {}) {
const KEY = 'com.cumulocity.authn';
const xsrfToken = this.xsrfToken;
let token = this.authTokenFromCookie;
if (!token && this.authTokenFromHeader) {
token = this.authTokenFromHeader.replace('Basic ', '').replace('Bearer ', '');
}
const ext = (config.ext = config.ext || {});
ext[KEY] = Object.assign(ext[KEY] || {}, { token, ...(xsrfToken ? { xsrfToken } : undefined) });
return config;
}
logout() {
if (this.authTokenFromCookie) {
delete this.authTokenFromCookie;
}
if (this.authTokenFromHeader) {
delete this.authTokenFromHeader;
}
if (this.xsrfToken) {
delete this.xsrfToken;
}
}
getCookieValue(headers, name) {
try {
const value = headers && headers.cookie && headers.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
return value ? value.pop() : undefined;
}
catch (ex) {
return undefined;
}
}
}
exports.MicroserviceClientRequestAuth = MicroserviceClientRequestAuth;
//# sourceMappingURL=MicroserviceClientRequestAuth.js.map