Sign the given claims

@param user the user to create the claims from
@return the created and signed JSON Web Token as string
974094
public String signToken(AuthenticatedUser user) {
        Date expiry = new Date(System.currentTimeMillis() + this.jwtTimeout);
        JWTClaimsSet claimsSet = user.toClaimSet(this.jwtIssuer, expiry);
        SignedJWT jwt = this.signToken(claimsSet);
        return jwt.serialize();
    }
990821
function(req, res, user) {
      waterlock.logger.debug('user registration success');
      if (!user) {
        waterlock.logger.debug('registerSuccess requires a valid user object');
        return res.serverError();
      }

      var address = this._addressFromRequest(req);

      var attempt = {
        user: user.id,
        successful: true
      };

      _.merge(attempt, address);

      waterlock.Attempt.create(attempt).exec(function(err) {
        if (err) {
          waterlock.logger.debug(err);
        }
      });

      // store user in && authenticate the session
      req.session.user = user;
      req.session.authenticated = true;

      // now respond or redirect
      var postResponse = this._resolvePostAction(waterlock.config.postActions.register.success, user);

      if (postResponse === 'jwt') {
        //Returns the token immediately
        var jwtData = waterlock._utils.createJwt(req, res, user);

        Jwt.create({token: jwtData.token, uses: 0, owner: user.id}).exec(function(err){
          if(err){
            return res.serverError('JSON web token could not be created');
          }

          var result = {};

          result[waterlock.config.jsonWebTokens.tokenProperty] = jwtData.token;
          result[waterlock.config.jsonWebTokens.expiresProperty] = jwtData.expires;

          if (waterlock.config.jsonWebTokens.includeUserInJwtResponse) {
            result['user'] = user;
          }

          res.json(result);
        });
      }else if (typeof postResponse === 'string' && this._isURI(postResponse)) {
        res.redirect(postResponse);
      } else {
        res.ok(postResponse);
      }
    }
769129
public static  UUID getOrCreateUserToken() {
        UUID userToken;
        if (Request.getPerThreadRequestData().getRequestId() != null) {
            try {
                userToken = UUID.fromString(Request.getPerThreadRequestData().getRequestId());
            } catch (final IllegalArgumentException ignored) {
                userToken = UUIDs.randomUUID();
            }
        } else {
            userToken = UUIDs.randomUUID();
        }
        return userToken;
    }
510417
public GitkitUser updateUser(GitkitUser user)
      throws GitkitClientException, GitkitServerException {
    try {
      return jsonToUser(rpcHelper.updateAccount(user));
    } catch (JSONException e) {
      throw new GitkitServerException(e);
    }
  }
225361
public void saveUser(User user) {
        LOG.trace("Trying to create a new user");
        // encode the raw password using bcrypt
        final String pwHash = passwordEncoder.encode(user.getPassword());
        user.setPassword(pwHash);
        dao.saveOrUpdate(user);
        LOG.info("Created the user " + user.getAccountName());
    }
683591
public static @Nonnull ApiTokenStats load(@Nonnull User user) {
        // even if we are not using statistics, we load the existing one in case the configuration
        // is enabled afterwards to avoid erasing data
        
        ApiTokenStats apiTokenStats = null;
        
        File userFolder = user.getUserFolder();
        if (userFolder != null) {
            apiTokenStats = internalLoad(userFolder);
        }
        
        if (apiTokenStats == null) {
            apiTokenStats = new ApiTokenStats();
        }
        
        apiTokenStats.user = user;
        
        return apiTokenStats;
    }
961862
public JwwfServer bindWebapp(final Class<? extends User> user, String url) {
		if (!url.endsWith("/"))
			url = url + "/";

		context.addServlet(new ServletHolder(new WebClientServelt(clientCreator)), url + "");
		context.addServlet(new ServletHolder(new SkinServlet()), url + "__jwwf/skins/*");
		ServletHolder fontServletHolder = new ServletHolder(new ResourceServlet());
		fontServletHolder.setInitParameter("basePackage", "net/magik6k/jwwf/assets/fonts");
		context.addServlet(fontServletHolder, url + "__jwwf/fonts/*");
		context.addServlet(new ServletHolder(new APISocketServlet(new UserFactory() {

			@Override
			public User createUser() {
				try {
					User u = user.getDeclaredConstructor().newInstance();
					u.setServer(jwwfServer);
					return u;
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		})), url + "__jwwf/socket");

		for (JwwfPlugin plugin : plugins) {
			if (plugin instanceof IPluginWebapp)
				((IPluginWebapp) plugin).onWebappBound(this, url);
		}

		return this;
	}
305722
@Override
    public Builder claimFrom(String jsonOrJwt) throws InvalidTokenException {
        isValidToken(jsonOrJwt);
        String decoded = jsonOrJwt;
        if (JwtUtils.isBase64Encoded(jsonOrJwt)) {
            decoded = JwtUtils.decodeFromBase64String(jsonOrJwt);
        }
        boolean isJson = JwtUtils.isJson(decoded);

        if (!isJson) {
            String jwtPayload = JwtUtils.getPayload(jsonOrJwt);
            decoded = JwtUtils.decodeFromBase64String(jwtPayload);
        }

        // boolean isJwt = JwtUtils.isJwtToken(jsonOrJwt);
        // String decoded = jsonOrJwt;
        // if (isJwt) {
        // String jwtPayload = JwtUtils.getPayload(jsonOrJwt);
        // decoded = JwtUtils.decodeFromBase64String(jwtPayload);
        //
        // } else {
        // // either decoded payload from jwt or encoded/decoded json string
        // if (JwtUtils.isBase64Encoded(jsonOrJwt)) {
        // decoded = JwtUtils.decodeFromBase64String(jsonOrJwt);
        // }
        // }

        // String formattedString = JwtUtils.fromBase64ToJsonString(jsonOrJwt);
        if (decoded != null) {
            Map claimsFromAnother = null;
            try {
                claimsFromAnother = JwtUtils.claimsFromJsonObject(decoded);
            } catch (JoseException e) {
                String err = Tr.formatMessage(tc, "JWT_INVALID_TOKEN_ERR");
                throw new InvalidTokenException(err);
            }
            if (claimsFromAnother != null && !claimsFromAnother.isEmpty()) {
                claims.putAll(claimsFromAnother);
            }
        }
        return this;
    }
371466
public JsAPISignature createJsAPISignature(String url){
        if(jsAPITicket == null || jsAPITicket.expired()) {
            getJsAPITicket();
        }

        long timestamp = System.currentTimeMillis() / 1000;
        String nonce = RandomStringGenerator.getRandomStringByLength(16);
        String ticket = jsAPITicket.getTicket();

        try {
            String signature = SHA1.getSHA1("jsapi_ticket=" + ticket + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + url);

            JsAPISignature jsAPISignature = new JsAPISignature();
            jsAPISignature.setAppId(wxClient.getClientId());
            jsAPISignature.setNonce(nonce);
            jsAPISignature.setTimestamp(timestamp);
            jsAPISignature.setSignature(signature);
            jsAPISignature.setUrl(url);
            return jsAPISignature;
        } catch (AesException e) {
            logger.error("createJsAPISignature failed", e);
            throw new WxRuntimeException(999, e.getMessage());
        }
    }
738074
@Override
    public Builder subject(String username) throws InvalidClaimException {
        if (username != null && !username.isEmpty()) {

            claims.put(Claims.SUBJECT, username);
        } else {
            String err = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_VALUE_ERR", new Object[] { Claims.SUBJECT, username });
            throw new InvalidClaimException(err);
        }
        return this;
    }
512812
function generateForUser(user, existingToken) {
        existingToken = existingToken || {};

        var privateKey = config.security.token.privateKey;
        var decryptedToken = _.extend(existingToken, { _id: user._id, authToken: user.authToken });

        return jsonwebtoken.sign(decryptedToken, privateKey);
    }
890792
def create_token(self, user):
        
        # The password is expected to be a secure hash but we hash it again
        # for additional safety. We default to MD5 to minimize the length of
        # the token. (Remember, if an attacker obtains the URL, he can already
        # log in. This isn't high security.)
        h = crypto.pbkdf2(
            self.get_revocation_key(user),
            self.salt,
            self.iterations,
            digest=self.digest,
        )
        return self.sign(self.packer.pack_pk(user.pk) + h)
886881
def build_signature(self, user_api_key, user_secret, request):
        """"""
        path = request.get_full_path()
        sent_signature = request.META.get(
            self.header_canonical('Authorization'))
        signature_headers = self.get_headers_from_signature(sent_signature)
        unsigned = self.build_dict_to_sign(request, signature_headers)

        # Sign string and compare.
        signer = HeaderSigner(
            key_id=user_api_key, secret=user_secret,
            headers=signature_headers, algorithm=self.ALGORITHM)
        signed = signer.sign(unsigned, method=request.method, path=path)
        return signed['authorization']
140269
public QYResultType create(QYUser user){
        BeanUtil.requireNonNull(user, "user is null");
        String url = BASE_API_URL + "cgi-bin/user/create?access_token=#";
        BaseResponse response = executePost(url, user.toJsonString());
        return QYResultType.get(response.getErrcode());
    }
732690
public String create(Consumer<JWTCreator.Builder> jwtBuilderConsumer) {
        Date issueTime = new Date();
        Date expirationTime = new Date(issueTime.getTime() + defaultExpirationMs);
        JWTCreator.Builder builder = JWT.create()
                // opinionated creation, we enforce using an expiration
                .withIssuer(issuer)
                .withIssuedAt(issueTime)
                .withExpiresAt(expirationTime);
        // apply any additional token customisation
        jwtBuilderConsumer.accept(builder);
        return sign(builder);
    }
938367
public static Optional<Principal> withWebIdClaim(final Claims claims) {
        final String webid = claims.get(WEBID, String.class);
        if (webid == null) return empty();
        LOGGER.debug("Using JWT claim with webid: {}", webid);
        return of(new OAuthPrincipal(webid));
    }
816260
public static UserCredentialsDto fromUser(User user) {
    UserCredentialsDto result = new UserCredentialsDto();
    result.setPassword(user.getPassword());
    return result;
  }