What is the best way to implement Basic Auth?
Hello,
I have been using lux for the past few weeks to build a REST server for my school project, despite the missing docs, I think this framework is awesome and easy to learn.
One thing I cant figure out however is how to implement basic auth however. I have tried using the example social media app, and various other methods, but I cant seem to get this working.
My idea was that there is a 'authentication' middleware file, which I call with the 'beforeAction' hook on my application controller (like described in the old documentation). I would then take the authentication info from the request header and query the database to look for the user.
Getting the auth info from the header is easy enough, but I cant figure out how I should query the database from the middleware file.
Could you please describe how I should implement basic auth in lux?
Thank you
Hey,
Glad to hear your enjoying Lux! 😃
You can import your User model into the file where your middleware function is declared and do something like the following example.
import User from '../models/user';
// Stop processing request and return 401 unauthorized.
const unauthorized = () => 401;
export default async function authenticate(req) {
const authHeader = req.headers.get('Authorization');
if (!authHeader) {
return unauthorized();
}
const [username, password] = authHeader
.replace(/^basic\s/i, '')
.trim()
.split(':');
const user = await User
.first()
.where({ username });
if (!user || password !== user.password) {
return unauthorized();
}
}
Let me know if that answers your question.
Hey,
Thanks for the help! Authentication is working now!
Just for future reference, here is the final code (Apparently the 'authorization' header is case sensitive, and also the header data has to be converted from base64 encoding to ascii):
import User from '../models/user';
// Stop processing request and return 401 unauthorized.
const unauthorized = () => 401;
export default async function authenticate(req) {
const authHeader = req.headers.get('authorization');
if (!authHeader) {
return unauthorized();
}
// Convert base64 header to ascii, remove 'Basic ' prefix
const textHeader = Buffer.from(authHeader.replace(/^basic\s/i, ''), 'base64').toString('ascii');
const [name, password] = textHeader
.trim()
.split(':');
const user = await User
.first()
.where({ name });
if (!user || password !== user.password) {
return unauthorized();
}
}`
Awesome, thanks for sharing that!