JWT Filters\Hooks

We’re using JWT tokens to authenticate users accessing our API, we have application-specific checks and balances that must be done with each requests to ensure the user can still access the system, if not, then we need to return a 401.

The criteria we’re using to check is the username stored within the JWT and we’d need to access the database/redis with each request to validate the user’s access to the system.

What is the best way to accomplish this?

JWT is normally authenticated when it’s created not when it’s used so the Issuer is the only Service that needs to verify the user before creating the token, validating token on use also mitigates some of JWT’s performance advantages which doesn’t normally require any I/O calls to authenticate.

You could validate the token and throw a HttpError.Forbidden() Exception in PopulateSessionFilter but I’ve also added an explicit ValidateToken callback which you could use in this commit.

Which will let you add custom logic like:

new JwtAuthProvider(AppSettings) {
    ValidateToken = (jwtBody, req) => 
        MyValidateUser(jwtBody["sub"], req.TryResolve<IRedisClientsManager>())

Where MyValidate is your custom method that returns a bool whether the JWT is valid or not.

This change is available from v4.5.7 that’s now available on MyGet.

Thank you mythz! Your response has been extremely helpful in shaping our design decisions. I have just one more question regarding JWT.

Upon doing some research I stumbled upon some information on the cookie, “ss-tok”; currently, our API is not returning the cookie, “ss-tok” upon successful authentication. Our current method of retrieving the JWT token from the API is to call the /auth endpoint from our frontend client after the user has been authenticated.

Is there a way to force SS (our API) to automatically send the JWT upon successful authentication regardless of the provider (login/OAuth/OAuth2) without having to call the /auth endpoint?

My goal is to make our API completely stateless and disable the other cookies via (AllowSessionCookies = false).

To tell ServiceStack to use the ss-tok Cookie you need to specify UseTokenCookie=true on Authentication, this also removes the our Session from the App Servers Cache as now the Users Authenticated Session is contained solely in the JWT Cookie.

You can only force ServiceStack to use TokenCookie when you’ve Authenticated by sending the Authenticate DTO. For OAuth there is no AuthenticateResponse returned so you need to call ConvertSessionToToken or POST to /session-to-token which converts your current Authenticated Session into a JWT Token and removes the Authenticated Session from the Server so the only State left is in the Cookie.