This article is from Play Framework (Java) Advent Calendar 2016.
There is an annotation for CSRF measures in Play Framework, but I would like to be able to support other than CSRF.
Therefore, Saiki's Double Submit Countermeasures is very helpful for double submit. I will write how to implement the token check method in this article in Play Framework! !!
I think there are various requirements for tokens, but this time we will generate a 32-character alphanumeric token.
public static String setToken(){
String token = RandomStringUtils.randomAlphanumeric(32);
Cache.set("token", token);
return token;
}
Java Use a class that generates a certain random number and store the generated token in Cache! !!
The generated token is held by the hidden attribute on the client side, When submitting, it confirms with the token stored in Cache.
public static Boolean isToken(String clientToken) {
Boolean isToken = true;
String cacheToken = (String) Cache.get("token");
if (cacheToken == null || "".equals(cacheToken)) {
isToken = false;
} else {
if (!cacheToken.equals(clientToken)) {
isToken = false;
}
}
Cache.remove("token");
return isToken;
}
If it matches the token returned from the client, it returns true and Returns false if they do not match.
Now you can handle double submit! !!
Recommended Posts