Alex G.P.
Alex G.P.

Reputation: 10028

Authorization Bearer after basic

I have backend server "protected" with basic http auth and exposed number of REST API endpoint. Some endpoint protected with JWT token that acquired on login process. JWT token sends from client in Authorization: Bearer TOKEN header.

Question: is it possible to have both auth types in the same moment - http auth and JWT? Only pass Bearer in different header?

Upvotes: 1

Views: 2352

Answers (1)

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

It really depends on your backend. You will need to modify it a bit.

Solution with passport-jwt

You can specify the Bearer Authorization header with a different name, like X-Authorization and then have somewhere ( let's assume you use passport ) configured that the JWT will be delivered via another request header

const jwt = ExtractJwt.fromHeader( "X-Authorization" );

Then the two headers won't collide and you will be able to have a user authenticated with JWT and / or Basic Auth.

Even if you are not using passport for JWT authorization, the basic idea is still valid.

Generic solution

Or you can simply use a middleware to extract the authorisation. Similar to how express-bearer-token works.

app.use( function( req, res, next ) {

    var headerName = "X-Authorization";

    if (req.headers && req.headers[headerName]) {
        var parts = req.headers[headerName].split(' ');
        if (parts.length === 2 && parts[0] === "Bearer") {
            req["token"] = parts[1];
        }
    }

    next();

} );

Upvotes: 3

Related Questions