This is how I do it with Spark + auth0 jwt. Please bear with me as it is not 100% java but Nashorn javascript (for java8)...
I've a function to handle post to /authenticate, and this returns a JSON output. The client is supposed to grab this output and store it into local storage.
_post('authenticate', function (req,res) {
var username = req.queryParams('username');
var password = req.queryParams('password');
var authenticated, out;
if (username && password) {
authenticated = _authenticate(username, password);
if (authenticated) {
out = { success: authenticated, token: _create_jwt(username) };
} else {
out = { success: false, reason: 'Wrong credentials' };
}
} else {
_halt(401);
}
res.type("application/json");
return JSON.stringify(out);
});
Here are the underlying functions:
Object.prototype._authenticate = function (username, password) {
var authenticated;
try {
var cu = SecurityUtils.getSubject();
var cs = cu.getSession();
cu.login(new UsernamePasswordToken(username, password));
authenticated = cu.isAuthenticated();
cu.logout();
}
catch(e) {
authenticated = false;
}
finally {
return authenticated;
}
}
and jwt related functions:
var _SECRET = '$3CR37';
var _EXPIRY = 12 * 3600 * 1000;
Object.prototype._create_jwt = function (username) {
var jwt;
var token = new HashMap();
token.uid = username;
token.role = 1;
token.exp = (new Date()).getTime() + _EXPIRY;
try {
var signer = new JWTSigner(_SECRET);
jwt = signer.sign(token);
}
catch(e) {
// undefined as default value
}
finally {
return jwt;
}
}
Object.prototype._verify_jwt = function (jwt) {
var verification;
try {
var verifier = new JWTVerifier(_SECRET);
verification = verifier.verify(jwt);
// 3 possible invalidations of token
if (!(verification.exp >= new Date())) { verification = undefined; }
if (verification.uid === null) { verification = undefined; }
if (verification.role === null) { verification = undefined; }
}
catch(e) {
// undefined as default value
}
finally {
return verification;
}
}
Now my application is a single web page application: if I get a status 401, the client pops back the login dialog, I've no redirection...
The client will send the auth token inside the header. It's not related to a 'after' filter.
_before('data/*', function (req,res) {
var jwt = req.headers('authorization');
if (jwt) {
if (_verify_jwt(jwt) !== undefined) {
// PASS 200
} else {
_halt(401);
}
} else {
_halt(401);
}
});
I used ExtJS for the client. I need to port this server code to java if you wish to use it, and I'm in the process of writing a small angular client code as well.
Next week at best...