Comments (3)
I just ran into this issue trying to grab the access token from the headers of a CORS request in my
AuthProvider when I have CORS middleware set in the config.
To clarify, I have the following in my AuthProvider:
@injectable()
export default class PlayerAuthProvider implements interfaces.AuthProvider {
async getUser(req: Request, res: Response, next: NextFunction): Promise<interfaces.Principal> {
let accessTokenFromClient = req.headers["x-auth-token"];
which is missing the header, therefore returns 401 for a CORS request, given the following setup that uses setConfig:
const server = new InversifyExpressServer(container, null, null, null, PlayerAuthProvider);
server.setConfig((app) => {
app.use(cors({origin: true}));
app.options('*', cors());
app.use(bodyParser.json());
});
However, it goes on to successfully validate the token and populate the Principal, using the following setup that configures an express app and passes it as an argument:
const app = express();
app.use(cors({origin: true}));
app.options('*', cors());
app.use(bodyParser.json());
const server = new InversifyExpressServer(container, null, null, app, PlayerAuthProvider);
I have found that re-arranging the code in the build
(as mentioned by @geersch) to setup the config first solves the issue, as shown below:
// register server-level middleware before anything else
if (this._configFn) {
this._configFn.apply(undefined, [this._app]);
}
this._app.all("*", (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
(async () => {
const httpContext = await _self._createHttpContext(req, res, next);
...
next();
})();
});
I was thinking about opening a PR with this fix, but wanted to search it in the issues first, at which point, I ended up here.
I'd still be happy to submit a PR, but I wanted to at least post on here first and see if there's any reply. I'm especially curious whether this is a valid solution, or rather if there is a legitimate reason that the http context is created before the server middleware is registered. Don't wanna break anything; this library rocks! 😄❤️
from inversify-express-utils.
yep, I've faced with the same issue
from inversify-express-utils.
Error not handled by .setErrorConfig((app) => app.use(errorHandler)) which is generated by interfaces.AuthProvider implimenting class in inversify-express-utils
My app is crashing down here is the code of errorHandler and CustomAuthProvider
//errorHandler
const errorHandler = (err: any, req: Request, res: Response, next: NextFunction) => {
console.log("Error handler called");
let error = err as ApiError;
if (!(error instanceof ApiError)) {
error = new ApiError(
500,
err.message || "Something went wrong",
err,
err.stack);
}
// Now we are sure that the `error` variable will be an instance of ApiError class
const response = new ApiResponse(
error.statusCode,
false,
error.message,
//...(process.env.NODE_ENV === "development" ? { stack: error.stack } : {}), // Error stack traces should be visible in development for debugging
error.errors,
);
logger.error(`${error.errors}
${error.stack}`);
//removeUnusedMulterImageFilesOnError(req);
// Send error response
return res.status(response.statusCode).json(response);
};
//authprovider
@Injectable()
export class CustomAuthProvider implements interfaces.AuthProvider {
@inject(TYPES.IAuthService)
private readonly _authService!: IAuthService;
public async getUser(
req: Request,
res: Response,
next: NextFunction
): Promise<interfaces.Principal> {
try {
const token = req.headers["x-token"]
if (!token) {
throw new ApiError(401, "Unauthorized");
}
const user = await this._authService.getUserByToken(token as string);
console.log("CustomAuthProvider", token);
const principal = new Principal(user);
return principal;
} catch (error) {
console.log("CustomAuthProvider", error);
throw new ApiError(401, "Unauthorized");
}
}
}
from inversify-express-utils.
Related Issues (20)
- Injection scope for controller (singleton instead request scoped)
- Per-controller error handling HOT 1
- Release of a new npm version with peer dependency Express 4.17.0+ HOT 5
- Breaking change was introduced - interfaces.ts no longer exports an interface object HOT 3
- Latest inversify-express-utils is throwing build errors HOT 3
- Inversify Express controller inheritance fail if inheriting from more than 1 controller
- [inversify-express-utils] - No support for @controller on inevrfisy-binding-decorators? HOT 1
- Error trying to instantiate controller in a test (Error: No matching bindings found for serviceIdentifier: Symbol(HttpContext)) HOT 1
- inversify-express-utils, support of express 4.17.1 HOT 1
- [Inversify Express Utils] Controller is Reconstructed on Every Request HOT 1
- Inversify-Express-Untils Cannot Build Multiple Servers HOT 1
- Is inversify-express-utils no longer under maintenance? HOT 1
- integrating inversify-express-utils with inversify-socket-utils
- inversify-express-utils: BaseHttpController's conflict should take an argument
- [inversify-express-utils] AuthProvider Unhandled Promise Rejection HOT 1
- [inversify-express-utils] allow to inject dependencies into middleware constructor HOT 2
- Adding route config while creating server doesn't assign mount path to baseurl property of express request object
- JsonContent doesn't send correctly HOT 7
- Can not inject dependency in my CustomAuthProvider HOT 1
- Breaking changes from TypeScript update HOT 6
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from inversify-express-utils.