auth on api endpoints

I'm reading the docs, but still confused as to how to enable cookie-based auth out of the box. The documentation says that if i set auth: true on the api endpoint, that i will have to parse the jwt myself. But if i set it to false then there will be no auth (see payments webhook for example) If i leave auth blank, you would think that it would by default do cookie auth right? https://wasp.sh/docs/advanced/apis#using-entities-in-apis
If auth is enabled, this will default to true and provide a context.user object. If you do not wish to attempt to parse the JWT in the Authorization Header, you should set this to false.
If auth is enabled, this will default to true and provide a context.user object. If you do not wish to attempt to parse the JWT in the Authorization Header, you should set this to false.
I've tried things many different ways but haven't gotten it to work 😦
30 Replies
kapa.ai
kapa.ai•5mo ago
Hi @Captain Incredible. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- You're right to be confused—the documentation around auth on custom API endpoints in Wasp can be a bit unclear. Here's what the knowledge sources say: - If you set auth: true on your API endpoint in main.wasp, Wasp will provide a context.user object to your handler, and authentication will be enforced. This means you do not need to parse the JWT or handle cookies yourself—Wasp does this for you. The docs state:
If auth is enabled, this will default to true and provide a context.user object. If you do not wish to attempt to parse the JWT in the Authorization Header, you should set this to false.
API Reference – Custom HTTP API Endpoints - If you set auth: false, no authentication will be performed, and context.user will not be available. This is useful for public endpoints like webhooks. - If you omit the auth field, it defaults to true (i.e., authentication is enabled and context.user is provided). Regarding cookie-based auth:
Wasp's default authentication mechanism (as of recent versions) uses sessions and cookies, not JWTs in the Authorization header. So, if you have authentication enabled in your app (via the auth field in your app declaration in main.wasp), and you set auth: true (or leave it blank) on your API endpoint, Wasp will handle cookie-based authentication for you. You do not need to parse JWTs or manually handle cookies. Example:
api fooBar {
fn: import { fooBar } from "@src/apis",
httpRoute: (GET, "/foo/bar"),
auth: true // or just omit this line, as it defaults to true
}
api fooBar {
fn: import { fooBar } from "@src/apis",
httpRoute: (GET, "/foo/bar"),
auth: true // or just omit this line, as it defaults to true
}
In your handler, you can access the authenticated user via context.user:
export const fooBar = (req, res, context) => {
if (!context.user) {
res.status(401).json({ error: "Unauthorized" });
return;
}
// ...your logic
};
export const fooBar = (req, res, context) => {
if (!context.user) {
res.status(401).json({ error: "Unauthorized" });
return;
}
// ...your logic
};
API Reference – Custom HTTP API Endpoints
Using the context.user object Summary:
- Set auth: true (or omit it) for cookie-based auth out of the box. - Wasp will provide context.user if the user is authenticated. - You do not need to parse JWTs or handle cookies manually. If you are still not getting context.user populated, double-check that your app's global auth config is set up correctly in main.wasp, and that your client is sending requests with credentials (cookies) included. If issues persist, there may be a bug or misconfiguration. Let me know if you need help debugging a specific case! ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Captain Incredible
Captain IncredibleOP•5mo ago
@kapa.ai I've created a middleware like follows: apiNamespace allEndpoints { middlewareConfigFn: import { middlewareConfig } from "@src/api/_middleware", path: "/api" } I have all my api endpoints in /src/api/endpoints/, _middleware is in /src/api/ then my _middleware file contains this: export const middlewareConfig: MiddlewareConfigFn = (config) => { // Return the default config to enable CORS, then add our custom middleware return new Map([ // Include the default middleware for CORS ...config, // Add our custom authentication middleware [ '/api/', async (req: Request, res: Response, next: NextFunction) => { try { // In Wasp API middleware, the user is available on the request object // after Wasp's auth middleware has processed the request let user = (req as any).user;

// If no user from Wasp's auth middleware, try to get user from our custom auth logic if (!user) { console.log('Middleware: No authentication found, returning 401'); return res.status(401).json({ error: 'Unauthorized: You must be logged in to access this resource.' }); } const path = req.path; const method = req.method;
// Strip /api prefix for path matching since our rules don't include it const pathWithoutApi = path.startsWith('/api/') ? path.substring(4) : path; // Define role-based access control rules based on path patterns const accessRules = { // Admin-only endpoints admin: { paths: [ '/admin', '/users', '/analytics', '/stats', // Admin operations '/getPaginatedUsers', '/updateIsUserAdminById', '/getDailyStats' ], roles: [UserRole.ADMIN], description: 'Admin access required' },...
kapa.ai
kapa.ai•5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Based on your code and the Wasp documentation, your approach to using an apiNamespace with a custom middlewareConfigFn is correct for applying middleware to all API endpoints under a specific path (e.g., /api). This is the recommended way to add custom middleware logic, such as authentication or role-based access control, to a group of endpoints in Wasp. Key points from the docs: - The apiNamespace declaration in main.wasp allows you to apply a middlewareConfigFn to all APIs under a given path. This is useful for things like CORS, authentication, or other cross-cutting concerns for a set of endpoints.
Example from the docs:
apiNamespace fooBar {
middlewareConfigFn: import { fooBarNamespaceMiddlewareFn } from "@src/apis",
path: "/foo/bar"
}

apiNamespace fooBar {
middlewareConfigFn: import { fooBarNamespaceMiddlewareFn } from "@src/apis",
path: "/foo/bar"
}

Customize Per-Path Middleware - Your middlewareConfigFn receives the current middleware config (a Map), and you can add or override middleware as needed. The docs show how to add custom middleware:
export const fooBarNamespaceMiddlewareFn = (middlewareConfig) => {
const customMiddleware = (_req, _res, next) => {
console.log('fooBarNamespaceMiddlewareFn: custom middleware')
next()
}
middlewareConfig.set('custom.middleware', customMiddleware)
return middlewareConfig
}

export const fooBarNamespaceMiddlewareFn = (middlewareConfig) => {
const customMiddleware = (_req, _res, next) => {
console.log('fooBarNamespaceMiddlewareFn: custom middleware')
next()
}
middlewareConfig.set('custom.middleware', customMiddleware)
return middlewareConfig
}

Customize Per-Path Middleware - The default middleware (including CORS) is already present, so if you want to keep it, you should return the original config with your additions, as you are doing. About accessing the user: - If your endpoints have auth: true (or omit the auth field, since it defaults to true), Wasp will run its auth middleware before your custom middleware, and the authenticated user will be available on the request object (e.g., req.user or context.user in the handler) Accessing the logged-in user. Caveats: - If you set auth: false on an endpoint, Wasp will not run its auth middleware, and req.user/context.user will not be set. - Your custom middleware should check for the presence of the user and handle unauthorized access as you are doing. Summary:
Your approach matches the documented Wasp pattern for per-path middleware. As long as your endpoints are under /api and have auth: true (or omit the field), your middleware will have access to the authenticated user via the request object. If you encounter issues where req.user is not set, double-check the auth field on your endpoints and ensure your global auth config is correct. If you need more advanced control, you can also customize middleware globally or per-endpoint, as described in the docs Middleware Customization. If you have a specific issue (e.g., req.user is always undefined), please provide more details about your endpoint declarations and global auth config. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Captain Incredible
Captain IncredibleOP•5mo ago
@kapa.ai i'm getting this issue: [ Server ] GET /auth/me 304 6.353 ms - - [ Server ] Middleware: Request path: /getAllTasksByUser [ Server ] Middleware: User object: undefined [ Server ] Middleware: Request cookies: undefined [ Server ] Middleware: Authorization header: Bearer 2ua232elrmyrbnwudhnflaithwrlnn64vkuhxsqw [ Server ] Middleware: Request headers: [ [ Server ] 'host', 'connection', [ Server ] 'sec-ch-ua-platform', 'authorization', [ Server ] 'user-agent', 'accept', [ Server ] 'sec-ch-ua', 'dnt', [ Server ] 'sec-ch-ua-mobile', 'origin', [ Server ] 'sec-fetch-site', 'sec-fetch-mode', [ Server ] 'sec-fetch-dest', 'referer', [ Server ] 'accept-encoding', 'accept-language' [ Server ] ] [ Server ] Middleware: No authentication found, returning 401
kapa.ai
kapa.ai•5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Based on your logs, it looks like your middleware is not seeing a user object on the request, and cookies are also undefined. Instead, you have an Authorization header with a Bearer token. Key points from Wasp's behavior and documentation: - Wasp's default authentication uses sessions and cookies, not JWTs in the Authorization header. If you are sending a Bearer token, Wasp will not automatically parse it and populate req.user unless you implement custom logic for JWT parsing.
- For Wasp to populate req.user (or context.user), the request must include the session cookie that Wasp sets after login. If you are using a tool or client that only sends an Authorization header, Wasp's built-in auth middleware will not recognize it by default and will not set the user object Accessing the logged-in user. - If you want to use cookie-based authentication (Wasp's default), ensure your client is sending the session cookie with the request. If you are testing with a tool like Postman or curl, make sure to include the cookie. - If you want to support JWTs in the Authorization header, you would need to implement custom middleware to parse the JWT and set the user object yourself. Wasp does not do this out of the box for custom API endpoints API Reference – Custom HTTP API Endpoints. Summary of what’s happening: - Your middleware is running, but since the request does not have the expected session cookie, Wasp's auth middleware does not set req.user. - The presence of an Authorization header with a Bearer token is ignored by default Wasp auth middleware. What you should do: - If you want to use Wasp's built-in auth, make sure your client sends the session cookie. - If you want to support Bearer tokens, you need to add custom logic to parse the JWT and set the user object in your middleware. If you need more details on how to implement custom JWT parsing, the knowledge sources do not provide a ready-made example, so you may need to refer to Express or Passport.js documentation for that part. Let me know if you need help with a specific approach! ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Captain Incredible
Captain IncredibleOP•5mo ago
can you show me how to support bearer tokens here? @kapa.ai can you show me how to support bearer tokens here?
kapa.ai
kapa.ai•5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I'm sorry, but the knowledge sources do not provide a complete, official example of how to implement Bearer token (JWT) authentication in Wasp middleware for custom API endpoints. The documentation and community discussions confirm that Wasp's default authentication uses cookies/sessions, and that supporting JWTs in the Authorization header requires custom logic, but they do not provide a step-by-step guide or code sample for this scenario. There is a partial example from a Discord thread showing how to generate a JWT and send it to the client, but it does not cover how to parse and verify the JWT from the Authorization header on incoming requests within Wasp's middleware system. The thread suggests that you would need to implement this yourself, possibly by using a custom middleware to extract and verify the token, then set the user on the request object, but no full implementation is given Best Practices for Implementing Auth System in Chrome Extension Connected to OpenSaaS. If you need to implement this, you would typically use a JWT library (like jsonwebtoken) in your middleware to verify the token and set the user, but again, the official Wasp docs do not provide a sanctioned example for this pattern. If you need further guidance, you may want to ask in the Wasp community or check for updates in the documentation. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Captain Incredible
Captain IncredibleOP•5mo ago
@kapa.ai i just don't understand why my cookie is undefined when my api auth field is true
kapa.ai
kapa.ai•5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- If your cookie is undefined when your API endpoint has auth: true, there are a few likely reasons based on the knowledge sources: 1. Client is not sending the cookie:
Wasp's authentication relies on a session cookie being sent with each request. If your client (browser, Postman, curl, etc.) is not including the cookie, the server will not see it and req.cookies will be undefined. Make sure your client is configured to send cookies with requests. For browsers, this usually happens automatically for same-origin requests, but for cross-origin requests, you must set credentials: "include" in your fetch/XHR options. 2. CORS and credentials:
If your frontend and backend are on different domains (or ports), you need to ensure CORS is configured to allow credentials, and your frontend must send requests with credentials. Otherwise, cookies will not be sent.
CORS middleware is required for the frontend to communicate with the backend.
Configuring Middleware 3. Session storage mechanism:
Wasp stores the session in localStorage on the client and in the database on the server. If you are expecting a cookie but Wasp is using localStorage, you won't see a cookie.
The session is stored in localStorage on the client and in the database on the server.
Auth Overview – Sessions 4. Custom API endpoints and cookies:
If you are using custom API endpoints and expecting cookies, ensure that your authentication method and client setup match Wasp's expectations. If you are using JWTs in the Authorization header, Wasp will not set cookies by default. Summary:
The most common reason is that the client is not sending the cookie, or Wasp is using localStorage for sessions instead of cookies. Double-check your client configuration and Wasp's auth setup. If you are using cross-origin requests, ensure CORS and credentials are set up correctly. If you need to switch to cookie-based sessions, note that Wasp currently uses localStorage for sessions by default, as described in the docs. There is ongoing discussion in the community about moving to cookie-based sessions, but as of now, localStorage is the default mechanism Auth Overview – Sessions. If you need more specific troubleshooting, please provide details about your client setup and how you are making requests. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Captain Incredible
Captain IncredibleOP•5mo ago
@kapa.ai i thought wasp included a library for sending api request that would automatically pass the cookie? 'import { api } from 'wasp/client/api';' and ' const response = await api.post('/api/createTask', requestBody);' so why would i need to set credentials: "include"?
kapa.ai
kapa.ai•5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- You're correct that Wasp provides an API client (import { api } from 'wasp/client/api') for making requests to your custom API endpoints. According to the documentation, this api client is a wrapper around Axios and is designed to work seamlessly with Wasp's authentication system, which uses sessions and cookies by default. When you use the api client from the browser, it should automatically send cookies with your requests, so you do not need to manually set credentials: "include" when using it in your React app:
To use the API from your client, including with auth support, you can import the Axios wrapper from wasp/client/api and invoke a call.
— Using the API from the Client
If you are using the api client as shown:
import { api } from 'wasp/client/api';

const response = await api.post('/api/createTask', requestBody);
import { api } from 'wasp/client/api';

const response = await api.post('/api/createTask', requestBody);
the cookie should be sent automatically, provided you are running the client and server in a way that allows cookies to be shared (e.g., same domain or properly configured CORS for cross-domain). You only need to worry about credentials: "include" if you are using fetch directly or another HTTP client that does not send cookies by default for cross-origin requests. The Wasp api client handles this for you. If cookies are still not being sent, double-check your CORS and domain setup, but you do not need to set credentials: "include" when using Wasp's api client in the browser as intended. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Captain Incredible
Captain IncredibleOP•5mo ago
@miho when you get in monday could you graciously end my suffering? 🙂
NEROX
NEROX•5mo ago
@Captain Incredible Wasp stores the session with wasp:sessionId in the Local Storage, maybe is this what are you looking for?
Captain Incredible
Captain IncredibleOP•5mo ago
no, i found that, for whatever reason the user is undefined on the backend. . And wasp is passing the bearer token(which it shouldn't because i'm trying to use cookie auth in the web) but the user isn't getting populated either way. @kapa.ai the real question is how to add RBAC to my app while still using wasps auth. I'm supporting a mobile client, and i see the expo example and that looks great. But what would happen if i wanted to add RBAC to that? Wouldn't most people implement this using wasps 'per path' middleware? In doing so they would lose the auth provided by wasp. So what other workarounds are there?
MEE6
MEE6•5mo ago
Wohooo @Captain Incredible, you just became a Waspeteer level 3!
kapa.ai
kapa.ai•5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- To add RBAC (Role-Based Access Control) to your Wasp app while still using Wasp's built-in authentication, the recommended approach is to leverage the user object provided by Wasp's auth system (context.user) in your server-side logic (queries, actions, and API endpoints). This allows you to check the user's role and enforce access control without losing Wasp's authentication features. How to implement RBAC with Wasp's auth: 1. Add a role field to your User entity in your Wasp data model. This is a common pattern and is mentioned in community discussions:
If you just need a couple of fixed roles, then it can be as easy as introducing role field on the User entity and checking its value.
Discord: Teams/Groups 2. Check the user's role in your operations or API handlers using context.user. For example:
export const someAction = async (args, context) => {
if (!context.user || context.user.role !== 'admin') {
throw new HttpError(403);
}
// ...rest of your logic
}

export const someAction = async (args, context) => {
if (!context.user || context.user.role !== 'admin') {
throw new HttpError(403);
}
// ...rest of your logic
}

This is the current recommended way, as described in the docs and community:
You can add role field to User entity, and you can then in your queries/actions check the value of that role and based on that make a decision if they should be able to execute that query/action or not.
Discord: How do you add authorization? 3. Mobile clients (e.g., Expo):
The Expo example works because it uses Wasp's auth system, and you can still use the same RBAC checks on the server side. The client just authenticates as usual; the server enforces RBAC. 4. Per-path middleware:
While you can use per-path middleware for RBAC, you do not lose Wasp's auth as long as your endpoints have auth: true (or omit the field, since it defaults to true). Wasp's auth middleware will run first, and your custom middleware will have access to req.user (or context.user).
If your endpoints are under /api and have auth: true (or omit the field), your middleware will have access to the authenticated user via the request object.
Middleware Customization Summary:
- The most straightforward and supported way to add RBAC is to check context.user.role in your server logic. - You can use per-path middleware for RBAC, and as long as auth: true is set, you will still have access to the authenticated user. - There is no need for a workaround; Wasp's auth and RBAC via user roles are designed to work together in this way. If you need more advanced or centralized RBAC, the Wasp team is considering future improvements (e.g., middleware-based or CASL integration), but for now, manual checks in your server logic are the recommended and supported approach RFC: Support for Permissions (Access Control). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Captain Incredible
Captain IncredibleOP•5mo ago
when i created a custom 'per path' middleware, the user object was undefined even with the default "auth: true". I'm not sure why I lose the user object in my middleware. @kapa.ai when i created a custom 'per path' middleware, the user object was undefined even with the default "auth: true". I'm not sure why I lose the user object in my middleware.
kapa.ai
kapa.ai•5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- When you create a custom "per path" middleware in Wasp, the user object (req.user or context.user) should still be available in your middleware if the API endpoints under that path have auth: true (or omit the field, since it defaults to true). Wasp's documentation states that its auth middleware will run first and populate the user object, and then your custom middleware will execute, allowing you to access the authenticated user for RBAC or other logic. From the docs:
If your endpoints are under /api and have auth: true (or omit the field), your middleware will have access to the authenticated user via the request object.
Customize Per-Path Middleware If you are finding that the user object is undefined in your per-path middleware, possible reasons include: - The endpoint has auth: false: In this case, Wasp will not run its auth middleware, so the user object will not be set. - The request is missing the session cookie: If the client does not send the session cookie, Wasp cannot authenticate the user and will not set the user object. - Middleware order or implementation issue: If your custom middleware is somehow running before Wasp's auth middleware, the user object would not be set yet. However, according to the docs, Wasp should handle the order correctly. If none of these apply and you are still seeing user as undefined, it may be a bug or an edge case not covered in the documentation. The knowledge sources do not provide further details or troubleshooting steps for this specific scenario. In summary:
With auth: true and a valid session, your per-path middleware should have access to the user object. If not, double-check your endpoint configuration and client requests. If the issue persists, it may require further investigation or reporting to the Wasp team. Customize Per-Path Middleware
API Reference – Custom HTTP API Endpoints ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Captain Incredible
Captain IncredibleOP•5mo ago
@kapa.ai what wasp code do i need to look at to see how wasp authenticates using the cookie, then passes it on to the next middleware (my custom middleware)
kapa.ai
kapa.ai•5mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I'm sorry, but the knowledge sources do not provide direct references to the specific Wasp source code files or internal implementation details that handle authentication using cookies and the middleware chaining process. The documentation explains the high-level behavior—Wasp uses sessions (stored in localStorage on the client and in the database on the server) and provides the authenticated user via context.user or req.user to subsequent middleware and handlers when auth: true is set—but it does not point to the actual code or describe the internal Express middleware order or implementation. If you want to understand the exact code path, you would need to look into Wasp's open-source repository, focusing on how it integrates authentication middleware with Express and how it attaches the user object to the request. However, this information is not covered in the provided knowledge sources. For more details on how Wasp's middleware system works at a high level, you can refer to the documentation on Configuring Middleware and Custom HTTP API Endpoints, but these do not include internal code references. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Captain Incredible, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Carlos
Carlos•5mo ago
hey @Captain Incredible I'm not monitoring this thread, @ tag me if you need human help or when you're done so I can mark as solved
Captain Incredible
Captain IncredibleOP•5mo ago
@Carlos Is there anything else I should try? I'd be happy to jump on a quick call and show you what's happening @Carlos just pinging for visibility, i'm still really eager to keep looking into this
Carlos
Carlos•5mo ago
hey sorry, i only check the discord here in work hours 🙂 i'm checking and your initial question is wrong
The documentation says that if i set auth: true on the api endpoint, that i will have to parse the jwt myself. But if i set it to false then there will be no auth (see payments webhook for example)
That is not what it means, sorry if it is a bit confusingly-phrased 🙏 If you set auth: true, we will parse the JWT for you. You should add your JWT as the Authorization header in the request
Captain Incredible
Captain IncredibleOP•5mo ago
Hey Carlos, thanks for the reply. Parsing the jwt was going to be my last resort. I was initially hoping to get cookie auth working on an API endpoint, when that didn't work, I switched to trying to parse the jwt, however it doesn't look like the parsing of the jwt is correct. I should see some jwt separators in the raw jwt, but I don't. So there must a bug in the wasp Haskell transpiler here. I've started looking at the wasp codebase but I don't have a good enough sense of it to start bugfixing myself unfortunately. Today I'll take the middleware out and see if I can get a basic API endpoint working with cookie auth or a valid jwt. I'm using the recommended client API library built with axios that your provide. It looks like it is attempting to pass the jwt for me
Carlos
Carlos•5mo ago
@miho if you have a bit of time we'd could get some input here 🙏
miho
miho•5mo ago
Lemme answer some basics first: 1. Wasp doesn't use cookies for its auth 2. You can't really use cookies out of the box with Wasp if the client and the server have separate domains 3. What we store in the localStorage is not a JWT, but a session ID since we use session based auth which we compare with the stored session ID in the database What are you trying to achieve, to get the authenticated user with your custom API endpoint?
If you do not wish to attempt to parse the JWT in the Authorization Header, you should set this to false.
This bit in the docs is outdated, sorry about that! We should update that ASAP, created an issue for that: https://github.com/wasp-lang/wasp/issues/2931
Captain Incredible
Captain IncredibleOP•5mo ago
that helps, i'm trying to use the 'per path' middleware, i've created and 'api' directory which will hold all my api requests. I'm still struggling to get the user from the req object. It is undefined. In my middleware.ts file i have export const customRbacMiddleware: MiddlewareConfigFn = (middlewareConfig) => { middlewareConfig.set('custom.middleware', customMiddleware); return middlewareConfig; }; and const customMiddleware: express.RequestHandler = (_req: any, _res: any, next: any) => { try { let user = (_req).user; //... next(); } catch (err) { return _res.status(500).json({ error: 'Internal server error in middleware' }); } }; export const customRbacMiddleware: MiddlewareConfigFn = (middlewareConfig) => { middlewareConfig.set('custom.middleware', customMiddleware); return middlewareConfig; }; the middleware is being hit correctly before every endpoint, but i'm not sure on the syntax for getting the user.
MEE6
MEE6•5mo ago
Wohooo @Captain Incredible, you just became a Waspeteer level 4!
Captain Incredible
Captain IncredibleOP•5mo ago
Reading the docs, it is clear to me that you provide a context object to the api routes. But it's not as clear how to get this inside the middleware. I've tried renaming it context as well with no luck. @miho forgot to reply with the above comment to you. Alright, i fixed my issue. It turns out that I can't just add rbac to middleware. The order that middleware is ran matters. And wasp has decided that auth middleware will always run as the first non-global middleware. This means that I can't do rbac with wasp middleware yet. I've just moved my rbac into a function and called it at the top of every api endpoint. That solved my problem while still allowing me to centralize the rbac logic. thanks @miho @Carlos
miho
miho•5mo ago
I believe once we have RBAC natively, it'll be much more ergonomic for you https://github.com/wasp-lang/wasp/issues/2896

Did you find this page helpful?