Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package g3enterprises;
- import com.auth0.jwt.*;
- import com.auth0.jwt.algorithms.Algorithm;
- import com.auth0.jwt.exceptions.JWTVerificationException;
- import com.auth0.jwt.interfaces.DecodedJWT;
- import java.util.HashMap;
- public class G3JWT {
- HashMap<String, Object> headers;
- String user, pass;
- Algorithm algo;
- long iat = 0;
- final long EXPIRATION = 1209600L;
- final private String
- ISSUER = "SOME-ISSUER-STUFFS",
- SECRET = "SECRET",
- AUDIENCE = "SOME-AUDIENCE",
- V_USER = "USER",
- V_PASS = "PASS",
- NAME = "name",
- PASS = "pass",
- EXP = "exp",
- IAT = "iat",
- AUD = "aud",
- INVALID = "Invalid Credentials";
- private G3JWT() {
- this.algo = getAlgorithm();
- }
- public String getNewToken(String _user, String _pass) {
- this.user = _user;
- this.pass = _pass;
- if (isInvalidUser(user, pass)) {
- return INVALID;
- }
- /*
- * puts our own stuff inside the token
- */
- headers = getHeaders();
- return JWT.create()
- .withIssuer(ISSUER)
- .withHeader(headers)
- .sign(algo);
- }
- public String verifyToken(String token) {
- try {
- DecodedJWT jwt = getVerifier().verify(token);
- String token_user = jwt.getHeaderClaim(NAME).asString();
- String token_pass = jwt.getHeaderClaim(PASS).asString();
- long token_exp = jwt.getHeaderClaim(EXP).asInt();
- /*
- * is this user unauthorized
- */
- if (isInvalidUser(token_user, token_pass)) {
- return INVALID;
- }
- /*
- * if expired it returns invalid which will force the user to log
- * back in
- */
- if (token_exp < getCurrentTime()) {
- return INVALID;
- }
- /*
- * if all passed then refresh token
- */
- return this.getNewToken(token_user, token_pass);
- } catch (JWTVerificationException e) {
- e.printStackTrace();
- return INVALID;
- }
- }
- /*
- * creates the header info for the token
- */
- public HashMap<String, Object> getHeaders() {
- HashMap<String, Object> headers = new HashMap<String, Object>();
- iat = getCurrentTime();
- headers.put(AUD, AUDIENCE);
- headers.put(NAME, user);
- headers.put(PASS, pass);
- headers.put(EXP, iat + EXPIRATION);
- headers.put(IAT, iat);
- return headers;
- }
- /*
- * returns token verifier object
- */
- private JWTVerifier getVerifier() {
- return JWT.require(this.algo)
- .withIssuer(this.ISSUER)
- .build();
- }
- /*
- * returns encryption algorithm
- */
- public Algorithm getAlgorithm() {
- try {
- return Algorithm.HMAC256(SECRET);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- public long getCurrentTime() {
- return System.currentTimeMillis() / 1000l;
- }
- /*
- * checks if NOT authorized
- */
- public boolean isInvalidUser(String user, String pass) {
- /* if either doesn't match */
- return (!user.equals(V_USER) || !pass.equals(V_PASS));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement