Generate a unique token. The token is generated according to the
following pattern. NOnceToken = Base64 ( MD5 ( client-IP ":"
time-stamp ":" private-key ) ).

@param request HTTP Servlet request
962293
protected String generateNOnce(MobicentsSipServletRequest request) {

        long currentTime = System.currentTimeMillis();

        String nOnceValue = request.getRemoteAddr() + ":" +
            currentTime + ":" + key;

        byte[] buffer = null;
        synchronized (md5Helper) {
            buffer = md5Helper.digest(nOnceValue.getBytes());
        }
        nOnceValue = MD5_ENCODER.encode(buffer);

        return nOnceValue;
    }
272072
private void addPostParams(final Request request) {
        if (fieldType != null) {
            request.addPostParam("FieldType", fieldType);
        }

        if (uniqueName != null) {
            request.addPostParam("UniqueName", uniqueName);
        }
    }
232783
public void saveToken(CsrfToken t, HttpServletRequest request, HttpServletResponse response) {
		String ident = getIdentifierFromCookie(request);
		if (ident != null) {
			String key = ident.concat(parameterName);
			CsrfToken token = loadToken(request);
			if (token == null) {
				token = generateToken(null);
				if (Config.isCacheEnabled()) {
					cache.put(Config.getRootAppIdentifier(), key, token, (long) Config.SESSION_TIMEOUT_SEC);
				} else {
					localCache.put(key, new Object[]{token, System.currentTimeMillis()});
				}
			}
			storeTokenAsCookie(token, request, response);
		}
	}
1208275
public static String generateToken(final Integer apiKey, final String apiSecret)
            throws OpenTokException {

        //This is the default expire time we use for rest endpoints.
        final long defaultExpireTime = System.currentTimeMillis() / 1000L
                + TimeUnit.MINUTES.toSeconds(3);
        final JwtClaims claims = new JwtClaims();
        claims.setIssuer(apiKey.toString());
        claims.setStringClaim(ISSUER_TYPE, PROJECT_ISSUER_TYPE);
        claims.setGeneratedJwtId(); // JTI a unique identifier for the JWT.

        return getToken(claims, defaultExpireTime, apiSecret);
    }
687030
private void handle401(final YokeRequest request, final Handler<Object> next) {
        YokeResponse response = request.response();
        response.putHeader("WWW-Authenticate", "Basic realm=\"" + getRealm(request) + "\"");
        response.setStatusCode(401);
        next.handle("No authorization token");
    }
833304
public GetWaterMarkResponse getWaterMark(GetWaterMarkRequest request) {
        checkStringNotEmpty(request.getWatermarkId(), "The parameter watermarkId should NOT be null or empty string.");
        InternalRequest internalRequest =
                createRequest(HttpMethodName.GET, request, WATER_MARK, request.getWatermarkId());
        
        return invokeHttpClient(internalRequest, GetWaterMarkResponse.class);
    }
425383
public CreateNotificationResponse createNotification(CreateNotificationRequest request) {

        checkStringNotEmpty(request.getName(),
                "The parameter name should NOT be null or empty string.");
        checkStringNotEmpty(request.getEndpoint(),
                "The parameter endpoint should NOT be null or empty string.");

        InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, PATH_NOTIFICATION);
        String strJson = JsonUtils.toJsonString(request);
        byte[] requestJson = null;
        try {
            requestJson = strJson.getBytes(DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new BceClientException("Unsupported encode.", e);
        }

        internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(requestJson.length));
        internalRequest.addHeader(Headers.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
        internalRequest.setContent(RestartableInputStream.wrap(requestJson));
        return invokeHttpClient(internalRequest, CreateNotificationResponse.class);
    }
264153
public static String getToken(final HttpServletRequest request, final String key) {
		return (String) request.getSession(true).getAttribute(key);
	}
137587
private HashMap<String, String> getPropertyFromRequest(
            HashMap<String, String> tokens, HttpServletRequest request) {
        // Iterate through all of the other property keys looking for the first property
        // named like propname that has a value in the request
        HashMap<String, String> retHash = new HashMap<>();

        for (Map.Entry<String, String> entry : tokens.entrySet()) {
            String contextName = entry.getKey();
            String parmName = entry.getValue();
            String parmValue;
            if (request.getAttribute(parmName) != null) {
                // Upstream components (like servlet filters) may supply information
                // for the authentication process using request attributes.
                try {
                    parmValue = (String) request.getAttribute(parmName);
                } catch (ClassCastException cce) {
                    String msg = "The request attribute '" + parmName + "' must be a String.";
                    throw new RuntimeException(msg, cce);
                }
            } else {
                // If a configured parameter isn't provided by a request attribute,
                // check request parameters (i.e. querystring, form fields).
                parmValue = request.getParameter(parmName);
            }
            // null value causes exception in context.authentication
            // alternately we could just not set parm if value is null
            if ("password".equals(parmName)) {
                // make sure we don't trim passwords, since they might have
                // leading or trailing spaces
                parmValue = (parmValue == null ? "" : parmValue);
            } else {
                parmValue = (parmValue == null ? "" : parmValue).trim();
            }

            // The relationship between the way the properties are stored and the way
            // the subcontexts are named has to be closely looked at to make this work.
            // The keys are either "root" or the subcontext name that follows "root.". As
            // as example, the contexts ["root", "root.simple", "root.cas"] are represented
            // as ["root", "simple", "cas"].
            String key = (contextName.startsWith("root.") ? contextName.substring(5) : contextName);
            retHash.put(key, parmValue);
        }
        return (retHash);
    }
1154974
public boolean authenticate(HttpServletRequest request) throws MnoException {
		String authHeader = request.getHeader("Authorization");
		if (authHeader == null || authHeader.isEmpty()) {
			return false;
		}
		String[] auth = authHeader.trim().split("\\s+");

		if (auth == null || auth.length != 2 || !auth[0].equalsIgnoreCase("basic")) {
			return false;
		}
		byte[] decodedStr = DatatypeConverter.parseBase64Binary(auth[1]);
		String[] creds;
		try {
			creds = (new String(decodedStr, "UTF-8")).split(":");
		} catch (UnsupportedEncodingException e) {
			throw new MnoException("Could not decode basic authentication" + Arrays.toString(auth), e);
		}

		if (creds.length == 2) {
			return authenticate(creds[0], creds[1]);
		} else {
			return false;
		}
	}
558400
@Override
	public void process(Request request)
	{
		String correlationId = request.getHeader(CORRELATION_ID);

		// Generation on empty causes problems, since the request already has a value for Correlation-Id in this case.
		// The method call request.addHeader() only adds ANOTHER header to the request and doesn't fix the problem.
		// Currently then, the plugin only adds the header if it doesn't exist, assuming that if a client sets the
		// header to ANYTHING, that's the correlation ID they desired.
		if (correlationId == null) // || correlationId.trim().isEmpty())
		{
			correlationId = UUID.randomUUID().toString();
		}

		RequestContext.put(CORRELATION_ID, correlationId);
		request.addHeader(CORRELATION_ID, correlationId);
	}
46581
@RequestMapping(value = "/gettoken", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseMessage getToken(HttpServletRequest request, HttpServletResponse response) {
        String username = StringUtil.EMPTY_STRING;
        String password = StringUtil.EMPTY_STRING;
        ResponseMessage result = new ResponseMessage();
        try {
            JSONObject json = tgtools.web.util.RequestHelper.parseRequest(request);
            if (json.has("username")) {
                username = json.getString("username");
            }
            if (json.has("password")) {
                password = json.getString("password");
            }

            mUserService.validLoginUser(username, password);
            String token = mUserService.createToken(username, request.getRemoteAddr());
            result.setStatus(true);
            result.setData(token);
        } catch (Exception e) {
            result.setStatus(false);
            result.setData(e.getMessage());
        }
        return result;
    }
102576
public String newNonce(HttpRequest request)
    {
        long ts=request.getTimeStamp();
        long sk=nonceSecret;
        
        byte[] nounce = new byte[24];
        for (int i=0;i<8;i++)
        {
            nounce[i]=(byte)(ts&0xff);
            ts=ts>>8;
            nounce[8+i]=(byte)(sk&0xff);
            sk=sk>>8;
        }
        
        byte[] hash=null;
        try
        {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(nounce,0,16);
            hash = md.digest();
        }
        catch(Exception e)
        {
            log.fatal(this,e);
        }
        
        for (int i=0;i<hash.length;i++)
        {
            nounce[8+i]=hash[i];
            if (i==23)
                break;
        }
        
        return new String(B64Code.encode(nounce));
    }
1131030
public CsrfToken loadToken(HttpServletRequest request) {
		CsrfToken token = null;
		String ident = getIdentifierFromCookie(request);
		if (ident != null) {
			String key = ident.concat(parameterName);
			if (Config.isCacheEnabled()) {
				token = cache.get(Config.getRootAppIdentifier(), key);
			} else {
				Object[] arr = localCache.get(key);
				if (arr != null && arr.length == 2) {
					boolean expired = (((Long) arr[1]) + Config.SESSION_TIMEOUT_SEC * 1000) < System.currentTimeMillis();
					if (expired) {
						localCache.remove(key);
					} else {
						token = (CsrfToken) arr[0];
					}
				}
			}
		}
		return token;
	}
1194777
private function createToken(Request $request)
    {
        $tokenString = $request->headers->get($this->header);

        if ($this->header == self::HEADER_AUTH && 0 === strpos((string)$tokenString, 'Bearer ')) {
            $tokenString = substr($tokenString, 7);
        }

        if (!$tokenString) {
            return null;
        }

        return new JwtAuthenticationToken([], $tokenString);
    }
343842
@Override
    public ContentPattern<?> forRequest(Request request) {
        final String mimeType = request.getHeaders().getContentTypeHeader().mimeTypePart();
        if (mimeType != null) {
            if (mimeType.contains("json")) {
                return new EqualToJsonPattern(request.getBodyAsString(), ignoreArrayOrder, ignoreExtraElements);
            } else if (mimeType.contains("xml")) {
                return new EqualToXmlPattern(request.getBodyAsString());
            } else if (mimeType.equals("multipart/form-data")) {
                // TODO: Need to add a matcher that can handle multipart data properly. For now, just always match
                return new AnythingPattern();
            } else if (!determineIsTextFromMimeType(mimeType)) {
                return new BinaryEqualToPattern(request.getBody());
            }
        }

        return new EqualToPattern(request.getBodyAsString(), caseInsensitive);
    }
909659
private byte[] computeSignature(Request request) {
        String timestampAndQuery = request.getTimestamp() + '\n' +
                request.getSortedQueryParameters() + '\n';

        byte[] timestampAndQueryBytes = timestampAndQuery.getBytes(CHARSET_UTF8);
        byte[] bodyHashBytes = getSha256Hash(request.getData());

        return getHmacSha256Signature(appendArrays(timestampAndQueryBytes, bodyHashBytes));
    }