I'm new in angular and in Hapi. I would like to create a server and an app with just a simple login page. The user can log in and then he can access to some other pages.
So far, I have a Hapi server using hapi-auth-basic scheme authentication
'use strict';
const Hapi = require('Hapi');
const users = {
john: {
username: 'john',
password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm' // 'secret'
}
};
const validate = async (request, username, password, h) => {
const user = users[username];
if (!user) {
return { credentials: null, isValid: false };
}
const isValid = await Bcrypt.compare(password, user.password);
const credentials = { id: user.id, name: user.name };
return { isValid, credentials };
};
const main = async () => {
const server = new Hapi.Server({
port: 3000,
host: 'localhost',
routes: { cors: true },
debug: { request: ['*'] }
});
await server.register([
require('hapi-auth-basic')
]);
server.auth.strategy('simple', 'basic', { validate });
server.auth.default('simple');
server.route({
method: 'GET',
path: '/authenticate',
handler: function (request, h) {
return 'welcome';
}
});
await server.start();
return server;
};
main()
.then((server) => console.log(`Server listening on ${server.info.uri}`))
.catch((err) => {
console.error(err);
process.exit(1);
});
In Angular I have my login page and I like to send an authentication request to the api server.
Here is the function in auth-service.ts which call the server
getRequestWithBasicAuth(user: User): Observable<any> {
let data = btoa(user.name.toLowerCase() + ':' + user.password);
let headers = new HttpHeaders();
headers.append("Content-Type", "application/json");
headers.append("Authorization", "Basic " + data);
return this.http.get(this.authenticateUrl, {headers: headers})
.map((res: Response) => {
let jsonObj: any;
if (res.status === 204) {
jsonObj = null;
}
else if (res.status === 500) {
jsonObj = null;
}
else if (res.status === 200) {
jsonObj = res.json()
}
return [{ status: res.status, json: jsonObj }]
})
.catch(error => {
return Observable.throw(error);
});
}
Hapi console log this:
Debug: auth, unauthenticated, missing, simple core.js:122
Error: Unauthorized
I couldn't find any tutorial with the complete backend and frontend code. I tried several things and I'm starting to feel that basic authentication is not really made for what I want to do. But still, if I send the credentials correctly in the headers it should work, right ?
How can I send correctly the credentials ? I understood that with basic authentication, the user cannot logout. What kind of authentication scheme should I use ? Do you have any recommendation about tutorial or documentation which could help me to understand all this ?