<pre>
The JWT audience is used when generating a JWT id token for the backend.
</pre>

<code>string jwt_audience = 7;</code>
5990
public java.lang.String getJwtAudience() {
    java.lang.Object ref = "";
    if (authenticationCase_ == 7) {
      ref = authentication_;
    }
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs = 
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      if (authenticationCase_ == 7) {
        authentication_ = s;
      }
      return s;
    }
  }
299496
@Override
	public String getCustomCacheKeyFromJwtSSOToken(String encodedjwt) {
		// TODO Auto-generated method stub
		JwtSsoTokenUtils tokenUtil = getSimpleJwtSsoTokenUtils();
		if (encodedjwt != null) {
			return tokenUtil.getCustomCacheKeyFromToken(encodedjwt);
		}
		return null;
	}
125662
public static Map<String, Object> verify(String token, final RSAPublicKey pk) throws InvalidTokenException {
        // RS256签名验证器
        Verifier verifier = new Verifier() {
            @Override
            public boolean verifySignature(String content, String payload, String signature) {
                return JWT.verifySignature(content,signature,pk);
            }
        };
        return verify(token, verifier);
    }
321501
public String toJwt() {
        Map<String, Object> headers = new HashMap<>();
        headers.put("typ", "JWT");
        headers.putAll(this.getHeaders());

        JwtBuilder builder =
            Jwts.builder()
                .signWith(this.algorithm, this.secretKey)
                .setHeaderParams(headers)
                .setIssuer(this.issuer)
                .setExpiration(expiration);

        if (this.getClaims() != null) {
            for (Map.Entry<String, Object> entry : this.getClaims().entrySet()) {
                builder.claim(entry.getKey(), entry.getValue());
            }
        }

        if (this.getId() != null) {
            builder.setId(this.getId());
        }

        if (this.getSubject() != null) {
            builder.setSubject(this.getSubject());
        }

        if (this.getNbf() != null) {
            builder.setNotBefore(this.getNbf());
        }

        return builder.compact();
    }
808797
public String generateEmailConfirmationToken() {
		if (StringUtils.isBlank(identifier)) {
			return "";
		}
		Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier);
		if (s != null) {
			String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes());
			s.addProperty(Config._EMAIL_TOKEN, token);
			CoreUtils.getInstance().getDao().update(getAppid(), s);
			return token;
		}
		return "";
	}
1007401
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None):
    """"""
    assert user_id, "No user_id passed to generate_token()"
    assert isinstance(data, dict), "generate_token(data=) should be a dictionary"
    assert get_config().jwt_secret, "No JWT secret configured in pymacaron"

    if not issuer:
        issuer = get_config().jwt_issuer

    assert issuer, "No JWT issuer configured for pymacaron"

    if expire_in is None:
        expire_in = get_config().jwt_token_timeout

    if iat:
        epoch_now = iat
    else:
        epoch_now = to_epoch(timenow())
    epoch_end = epoch_now + expire_in

    data['iss'] = issuer
    data['sub'] = user_id
    data['aud'] = get_config().jwt_audience
    data['exp'] = epoch_end
    data['iat'] = epoch_now

    headers = {
        "typ": "JWT",
        "alg": "HS256",
        "iss": issuer,
    }

    log.debug("Encoding token with data %s and headers %s (secret:%s****)" % (data, headers, get_config().jwt_secret[0:8]))

    t = jwt.encode(
        data,
        get_config().jwt_secret,
        headers=headers,
    )

    if type(t) is bytes:
        t = t.decode("utf-8")

    return t
715907
public JwtClaims getJwtClaims(String jwt) throws JoseException {
        String methodName = "getJwtClaims";
        if (tc.isDebugEnabled()) {
            Tr.entry(tc, methodName, jwt);
        }
        JwtClaims jwtclaims = new JwtClaims();
        String payload = getJwtPayload(jwt);
        if (payload != null) {
            jwtclaims = getClaimsFromJwtPayload(jwt, payload);
        }
        if (tc.isDebugEnabled()) {
            Tr.exit(tc, methodName, jwtclaims);
        }
        return jwtclaims;
    }
1105456
static UserLimits getLimitsFromToken(HTTPServerConfig config, String jwtToken) {
    Objects.requireNonNull(jwtToken);
    try {
      String secretKey = config.getSecretTokenKey();
      if (secretKey == null) {
        throw new RuntimeException("You specified a 'token' parameter but this server doesn't accept tokens");
      }
      Algorithm algorithm = Algorithm.HMAC256(secretKey);
      DecodedJWT decodedToken;
      try {
        JWT.require(algorithm).build().verify(jwtToken);
        decodedToken = JWT.decode(jwtToken);
      } catch (JWTDecodeException e) {
        throw new AuthException("Could not decode token '" + jwtToken + "'", e);
      }
      Claim maxTextLengthClaim = decodedToken.getClaim("maxTextLength");
      Claim premiumClaim = decodedToken.getClaim("premium");
      boolean hasPremium = !premiumClaim.isNull() && premiumClaim.asBoolean();
      Claim uidClaim = decodedToken.getClaim("uid");
      long uid = uidClaim.isNull() ? -1 : uidClaim.asLong();
      return new UserLimits(
              maxTextLengthClaim.isNull() ? config.maxTextLength : maxTextLengthClaim.asInt(),
              config.maxCheckTimeMillis,
              hasPremium ? uid : null);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }
604610
public Authentication verifyIdToken(String idToken) throws InvalidTokenException, TokenExpiredException {
        CacheProvider cp = cp();
        Authentication authc = cp.get(idToken);
        if(null != authc) {
            if(!authc.isExpired()) {
                return authc;
            }else{
                cp.remove(idToken);
            }
        }
        
        //check is jwt token?
        boolean jwt = checkJwtToken(idToken);
        if(jwt) {
            authc = tp().verifyIdToken(idToken);
        }else{
            throw new InvalidTokenException("idToken is not and jwt token:"+idToken);
        }

        cp.put(idToken, authc, authc.getExpires());

        return authc;
    }
974478
public static SignedJWT generateJWToken(User user, App app) {
		if (app != null) {
			try {
				Date now = new Date();
				JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
				String userSecret = "";
				claimsSet.issueTime(now);
				claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000)));
				claimsSet.notBeforeTime(now);
				claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec()));
				claimsSet.claim(Config._APPID, app.getId());
				if (user != null) {
					claimsSet.subject(user.getId());
					userSecret = user.getTokenSecret();
				}
				JWSSigner signer = new MACSigner(app.getSecret() + userSecret);
				SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
				signedJWT.sign(signer);
				return signedJWT;
			} catch (JOSEException e) {
				logger.warn("Unable to sign JWT: {}.", e.getMessage());
			}
		}
		return null;
	}
1114918
function JWT (options) {
  options = options || {};
  var optionDefaults = {
    crypto: {
      algorithm: 'HS256'
    },
    header: {
      typ: 'JWT'
    },
    claims: {},
    validations: {}
  };
  _.defaultsDeep(options, optionDefaults);

  // -- Private
  var isHmac = false;
  var isSign = false;
  var isUnsecured = false;
  var validations;

  var algPrefix;
  var algBitLength;
  var algorithm;
  var crypto;

  var privateKey;
  var publicKey;
  var secret;

  var jwtClaims;
  var jwtHeader;

  function processKey (key) {
    if (!_.isUndefined(key)) {
      if (Buffer.isBuffer(key)) {
        return key.toString();
      } else {
        return key;
      }
    } else {
      return key;
    }
  }

  // -- Protected
  this.isHmac = function () {
    return isHmac;
  };

  this.isSign = function () {
    return isSign;
  };

  this.isUnsecured = function () {
    return isUnsecured;
  };

  this.getAlgorithm = function () {
    return algorithm;
  };

  this.getCrypto = function () {
    return crypto;
  };

  this.getHeader = function () {
    return jwtHeader;
  };

  this.getClaims = function () {
    return jwtClaims;
  };

  this.getSecret = function () {
    return secret;
  };

  this.getPrivateKey = function () {
    return privateKey;
  };

  this.getPublicKey = function () {
    return publicKey;
  };

  this.getValidations = function () {
    return validations;
  };

  // Public
  this.setValidations = function (obj) {
    validations = obj || {};
    return this;
  };

  this.setPrivateKey = function (key) {
    privateKey = processKey.bind(this)(key) || undefined;
    return this;
  };

  this.setPublicKey = function (key) {
    publicKey = processKey.bind(this)(key) || undefined;
    return this;
  };

  this.setSecret = function (sec) {
    if (!_.isUndefined(sec)) {
      if (Buffer.isBuffer(sec)) {
        secret =  sec.toString();
      } else {
        secret = sec;
      }
    } else {
      secret = sec;
    }
    return this;
  };

  this.setAlgorithm = function (alg) {
    if (_.has(JWT.getSupportedAlgorithms(), alg)) {
      jwtHeader = _.merge(options.header, { alg: alg.toUpperCase() });
      if (alg === 'NONE') {
        isHmac = false;
        isSign = false;
        isUnsecured = true;
        crypto = '';
      } else {
        algorithm = alg.toUpperCase();
        algPrefix = alg.substring(0,2);
        algBitLength = alg.substring(2,5);

        // Set type key
        if (algPrefix === 'RS'
            || algPrefix === 'ES'
            || algPrefix === 'PS'
        ) {
          isHmac = false;
          isSign = true;
          isUnsecured = false;
          crypto = 'RSA-SHA' + algBitLength;
        } else {
          isHmac = true;
          isSign = false;
          isUnsecured = false;
          crypto = 'sha' + algBitLength;
        }
      }
    } else {
      throw new JWTError(JWT_UNKNOWN_ALGORITHM + ' ' +  alg);
    }
    return this;
  };

  this.setClaims = function(claims) {
    jwtClaims = claims;
    return this;
  };

  //-- Initialization
  // Set header / alg
  this.setAlgorithm(options.crypto.algorithm);

  // Set secret / keys
  if (!_.isUndefined(options.crypto.secret)) {
    this.setSecret(options.crypto.secret);
  }

  if (!_.isUndefined(options.crypto.privateKey)) {
    this.setPrivateKey(options.crypto.privateKey);
  }

  if (!_.isUndefined(options.crypto.publicKey)) {
    this.setPublicKey(options.crypto.publicKey);
  }

  // Set default claims
  this.setClaims(options.claims);

  // Set Validations
  this.setValidations(options.validations);

  // Return instance
  return this;
}
621836
public String encodeForWebClient() throws MessageEncodeFailedException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "encodeForWebClient");
    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Encoding Web Message", ((MessageImpl)jmsMsg).debugMsg());

    // Make sure any transients necessary are written back to the message
    ((JsJmsMessageImpl)jmsMsg).updateDataFields(MfpConstants.UDF_ENCODE);

    StringBuffer result = new StringBuffer();

    // Version number
    result.append(1);

    // Message Id
    result.append('~');
    byte[] id = jmsMsg.getCorrelationIdAsBytes();
    if (id != null)
      HexString.binToHex(id, 0, id.length, result);

    // Message type
    result.append('~');
    String type = jmsMsg.getJmsxAppId();
    if (type == null || type.equals(MfpConstants.WPM_JMSXAPPID_VALUE))
      type = "SIB";
    URLEncode(result, type);

    // Message format
    result.append('~');
    result.append(jmsMsg.getFormat());

    // Topic
    result.append('~');
    String topic = jmsMsg.getDiscriminator();
    if (topic != null)
      URLEncode(result, topic);

    // Properties
    result.append('~');
    Set<String> names = jmsMsg.getPropertyNameSet();
    boolean first = true;
    for (Iterator<String> i = names.iterator(); i.hasNext(); ) {
      String name = i.next();

      // JMSXAppID is stored in the header field instead so ignore it here
      if (!name.equals(SIProperties.JMSXAppID)) {

        // All objects
        Object value = jmsMsg.getObjectProperty(name);
        if (value != null) {
          encodePair(result, name, value, first);
          first = false;
        }
      }
    }

    // Body
    if (jmsMsg instanceof JsJmsTextMessage)
      encodeTextBody(result, (JsJmsTextMessage)jmsMsg);
    else if (jmsMsg instanceof JsJmsBytesMessage)
      encodeBytesBody(result, (JsJmsBytesMessage)jmsMsg);
    else if (jmsMsg instanceof JsJmsObjectMessage)
      encodeObjectBody(result, (JsJmsObjectMessage)jmsMsg);
    else if (jmsMsg instanceof JsJmsStreamMessage)
      encodeStreamBody(result, (JsJmsStreamMessage)jmsMsg);
    else if (jmsMsg instanceof JsJmsMapMessage)
      encodeMapBody(result, (JsJmsMapMessage)jmsMsg);

    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Encoded as web data", result);
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "encodeForWebClient");
    return result.toString();
  }
657351
protected String internalGenerate(final JWTClaimsSet claimsSet) {
        JWT jwt;
        // signature?
        if (signatureConfiguration == null) {
            jwt = new PlainJWT(claimsSet);
        } else {
            jwt = signatureConfiguration.sign(claimsSet);
        }

        // encryption?
        if (encryptionConfiguration != null) {
            return encryptionConfiguration.encrypt(jwt);
        } else {
            return jwt.serialize();
        }
    }
729986
public static JWTPayload getPayload(String tokenString) {
        JWTPayload payload = null;
        String[] jwtParts = splitTokenString(tokenString);
        if (jwtParts.length >= 2) {
            WSJsonToken token = deserialize(jwtParts, tokenString);
            payload = new JWTPayload();
            fromJsonToken(token, payload);
        }
        return payload;
    }
642162
protected Token fetchSpecialId() {
        Token result = Token.create(Token.TokenType.SPECIAL_ID, input.current());
        result.addToTrigger(input.consume());
        while (isIdentifierChar(input.current())) {
            result.addToContent(input.consume());
        }
        return handleKeywords(result);
    }
652121
@Override
    public Builder jwtId(boolean create) {
        if (create) {
            String jti = JwtUtils.getRandom(16);
            claims.put(Claims.ID, jti);
        } else {
            claims.remove(Claims.ID);
        }

        return this;
    }
908149
@Post("json")
	public final Representation signUpUser(final Representation entity) {
		Request request = getRequest();
		Map<String, Object> requestAttributes = request.getAttributes();
		String passTypeIdentifier = (String) requestAttributes.get("passTypeIdentifier");
		String serialNumber = (String) requestAttributes.get("serialNumber");
		String authString = request.getChallengeResponse().getRawValue();

		LOGGER.debug("signUpUser: passTypeIdentifier: {}", passTypeIdentifier);
		LOGGER.debug("signUpUser: serialNumber: {}", serialNumber);
		LOGGER.debug("signUpUser - authString: {}", authString);

		Status responseStatus;
		Response response = getResponse();
		try {
			String payload = entity.getText();
			PKPersonalizePassPayload personalizePayload = jsonObjectMapper.readValue(payload, PKPersonalizePassPayload.class);

			LOGGER.debug("signUpUser - personalizePayload: {}", personalizePayload);
			responseStatus = handleSignUpUserRequest(passTypeIdentifier, serialNumber, authString, personalizePayload);
			if (responseStatus == Status.SUCCESS_OK || responseStatus == Status.SUCCESS_CREATED) {
				byte[] signedToken = signingUtil.signManifestFile(personalizePayload.getPersonalizationToken().getBytes(),
						getSingingInformation());
				InputRepresentation inputRepresentation = new InputRepresentation(new ByteArrayInputStream(signedToken));
				inputRepresentation.setMediaType(MediaType.APPLICATION_OCTET_STREAM);
				return inputRepresentation;
			}
		} catch (PKAuthTokenNotValidException e) {
			LOGGER.error("Error when processing signup request",e);
			responseStatus = Status.CLIENT_ERROR_UNAUTHORIZED;
		} catch (IOException | PKSigningException e) {
			LOGGER.error("Error when processing signup request",e);
			responseStatus = Status.SERVER_ERROR_INTERNAL;
		}
		response.setStatus(responseStatus);
		return null;

	}