Custom JWT Auth Provider

I am using the Azure Active Directory v2.0 endpoints for authentication into my application. My application then requests an access token and passes that onto my service stack api. I have written code, via custom request filter, that validates the access token. What I want to do, is convert this custom request filter into an auth plugin. All it needs to do is validate the token and populate the session.

Here is my global request handler code. How would I go about converting that into a custom auth provider.

    public class CustomRequestAttribute : RequestFilterAttribute
    {
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            var authenticationHeader = req.Headers[HttpHeaders.Authorization];
            var token = authenticationHeader.Substring(7);

            JwtSecurityToken jwt;

            try
            {
              JwtValidator.ValidateJwtToken(token);
            } catch (SecurityTokenException e)
            {
                throw e;
            }
        }
    }

I will worry about authorization piece later, as the roles and permissions are going to be coming from some place other than Azure Active Directory.

Have a look at how the JwtAuthProvider and its JwtAuthProviderReader is implemented for an example of an AuthProvider that validates JWT Tokens.

Since JWT AuthProviders authenticate per request you’ll need to implement IAuthWithRequest and its PreAuthenticate() which is what’s used to convert the incoming JWT and populate the Authenticated UserSession associated with the request, essentially with:

var session = CreateSessionFromPayload(req, jwtPayload);
req.Items[Keywords.Session] = session;

Thanks. I have implemented my own auth provider.

Since JWT is supposed to be sessionless, and I am creating a session, how does this session get killed? Does it do it automatically at the end of the request or after a certain amount of time?

JWT’s are “stateless”, i.e. the UserSession is encapsulated in the JWT Token itself and it only populates the Authenticated UserSession for the current request, i.e. it’s only accessible within the scope of the current request.

Excellent.

Thanks!!!