⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 spnegohttpurlconnection.java

📁 JAAS 例子代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
				break;
			}
		}
		if (values == null) {
			values = new ArrayList();
			values.add(value);
			requestProperties.put(key, values);
		}
		// 1.3-compatible.
		StringBuffer buffer = new StringBuffer();
		Iterator propertyValues = values.iterator();
		while (propertyValues.hasNext()) {
			buffer.append(propertyValues.next());
			if (propertyValues.hasNext()) {
				buffer.append(", ");
			}
		}
		connection.setRequestProperty(key, buffer.toString());
	}

	public String getRequestProperty(String key) {
		return connection.getRequestProperty(key);
	}

	public Map getRequestProperties() {
		Map map = new HashMap();
		Iterator entries = requestProperties.entrySet().iterator();
		while (entries.hasNext()) {
			Map.Entry entry = (Map.Entry) entries.next();
			map.put(entry.getKey(), Collections.unmodifiableList((List) entry
					.getValue()));
		}
		return Collections.unmodifiableMap(map);
	}

	public void setInstanceFollowRedirects(boolean instanceFollowRedirects) {
		connection.setInstanceFollowRedirects(instanceFollowRedirects);
	}

	public boolean getInstanceFollowRedirects() {
		return connection.getInstanceFollowRedirects();
	}

	public void setRequestMethod(String requestMethod) throws ProtocolException {
		connection.setRequestMethod(requestMethod);
		this.method = requestMethod;
	}

	public String getRequestMethod() {
		return connection.getRequestMethod();
	}

	public int getResponseCode() throws IOException {
		try {
			handshake();
		} catch (IOException ex) {
		}
		return connection.getResponseCode();
	}

	public String getResponseMessage() throws IOException {
		try {
			handshake();
		} catch (IOException ex) {
		}
		return connection.getResponseMessage();
	}

	public void disconnect() {
		connection.disconnect();
		handshakeComplete = false;
		connected = false;
	}

	public boolean usingProxy() {
		return connection.usingProxy();
	}

	public InputStream getErrorStream() {
		try {
			handshake();
		} catch (IOException ex) {
		}
		return connection.getErrorStream();
	}

	private int parseResponseCode() throws IOException {
		try {
			String response = connection.getHeaderField(0);
			int index = response.indexOf(' ');
			while (response.charAt(index) == ' ')
				index++;
			return Integer.parseInt(response.substring(index, index + 3));
		} catch (Exception ex) {
			throw new IOException(ex.getMessage());
		}
	}

	/**
	 * Do http handshake to authenticate user, modified by wayne
	 * @throws IOException
	 */
	private void doHandshake() throws IOException {
		connect();
		try {
			int response = parseResponseCode();
			if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
				return;
			}
			if (userCred == null) {
				throw new IOException("User Credential not found.");
			}

			if (userCred.isKerberosAuth()) {
				kerberosAuth(response);
			} else {
				ntlmAuth(response);
			}
		} finally {
			cachedOutput = null;
		}
	}

	/**
	 * Function added by wayne, to add kerberos authentication support
	 * @param response
	 * @throws IOException
	 */
	private void kerberosAuth(int response) throws IOException {
		try {
			InputStream errorStream = connection.getErrorStream();
			if (errorStream != null && errorStream.available() != 0) {
				int count;
				byte[] buf = new byte[1024];
				while ((count = errorStream.read(buf, 0, 1024)) != -1);
			}

			reconnect();
			SSOConf conf = SSOConf.getInstance();
			WebconsoleJaas.getInstance().action(new Krb5DeleAuthAction(conf
					.getValue(SSOConf.SERVER_PRINC), connection, cachedOutput,
					userCred));
		} catch (PrivilegedActionException ge) {
			ge.printStackTrace();
		} 
	}
	
	/**
	 * do NTLM negotiation with user name and password saved in user credential, modified by wayne
	 * @param response
	 * @return
	 * @throws IOException
	 */
	private NtlmMessage ntlmNegotiation(int response) throws IOException {
		authProperty = null;
		authMethod = null;
		InputStream errorStream = connection.getErrorStream();
		if (errorStream != null && errorStream.available() != 0) {
			int count;
			byte[] buf = new byte[1024];
			while ((count = errorStream.read(buf, 0, 1024)) != -1)
				;
		}

		String authHeader;
		if (response == HTTP_UNAUTHORIZED) {
			authHeader = "WWW-Authenticate";
			authProperty = "Authorization";
		} else {
			authHeader = "Proxy-Authenticate";
			authProperty = "Proxy-Authorization";
		}

		String authorization = null;
		List methods = (List) getHeaderFields0().get(authHeader);
		if (methods == null)
			return null;
		Iterator iterator = methods.iterator();
		while (iterator.hasNext()) {
			String currentAuthMethod = (String) iterator.next();
			if (currentAuthMethod.startsWith("NTLM")) {
				if (currentAuthMethod.length() == 4) {
					authMethod = "NTLM";
					break;
				}
				if (currentAuthMethod.indexOf(' ') != 4)
					continue;
				authMethod = "NTLM";
				authorization = currentAuthMethod.substring(5).trim();
				break;
			} else if (currentAuthMethod.startsWith("Negotiate")) {
				if (currentAuthMethod.length() == 9) {
					authMethod = "Negotiate";
					break;
				}
				if (currentAuthMethod.indexOf(' ') != 9)
					continue;
				authMethod = "Negotiate";
				authorization = currentAuthMethod.substring(10).trim();
				break;
			}
		}

		if (authMethod == null)
			return null;
		NtlmMessage message = (authorization != null) ? new Type2Message(Base64
				.decode(authorization)) : null;
		reconnect();

		SSOConf conf = SSOConf.getInstance();
		if (message == null) {
			message = new Type1Message();
			((Type1Message) message).setSuppliedDomain(conf
					.getValue(SSOConf.SERVER_DOMAIN));
			if (LM_COMPATIBILITY > 2) {
				message.setFlag(NtlmFlags.NTLMSSP_REQUEST_TARGET, true);
			}
		} else {
			String domain = conf.getValue(SSOConf.SERVER_DOMAIN);
			String workstation = conf.getValue(SSOConf.SERVER_WORKSTATION);
			String user = userCred.getName();
			String password = userCred.getPassword();
			Type2Message type2 = (Type2Message) message;
			message = new Type3Message(type2, password, domain, user,
					workstation, 0);
		}
		return message;
	}

	private void ntlmAuth(int response) throws IOException {
		//
		Type1Message type1 = (Type1Message) ntlmNegotiation(response);
		if (type1 == null)
			return; // no NTLM
		int attempt = 0;
		while (attempt < MAX_REDIRECTS) {
			connection.setRequestProperty(authProperty, authMethod + ' '
					+ Base64.encode(type1.toByteArray()));
			connection.connect(); // send type 1
			response = parseResponseCode();
			if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
				return;
			}

			Type3Message type3 = (Type3Message) ntlmNegotiation(response);
			if (type3 == null)
				return;
			connection.setRequestProperty(authProperty, authMethod + ' '
					+ Base64.encode(type3.toByteArray()));
			connection.connect(); // send type 3
			if (cachedOutput != null && doOutput) {
				OutputStream output = connection.getOutputStream();
				cachedOutput.writeTo(output);
				output.flush();
			}
			response = parseResponseCode();
			if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
				return;
			}
			attempt++;
			if (allowUserInteraction && attempt < MAX_REDIRECTS) {
				reconnect();
			} else {
				break;
			}
		}
		throw new IOException("Unable to negotiate NTLM authentication.");
	}

	private void reconnect() throws IOException {
		connection = (HttpURLConnection) connection.getURL().openConnection();
		connection.setRequestMethod(method);
		headerFields = null;
		Iterator properties = requestProperties.entrySet().iterator();
		while (properties.hasNext()) {
			Map.Entry property = (Map.Entry) properties.next();
			String key = (String) property.getKey();
			StringBuffer value = new StringBuffer();
			Iterator values = ((List) property.getValue()).iterator();
			while (values.hasNext()) {
				value.append(values.next());
				if (values.hasNext())
					value.append(", ");
			}
			connection.setRequestProperty(key, value.toString());
		}
		connection.setAllowUserInteraction(allowUserInteraction);
		connection.setDoInput(doInput);
		connection.setDoOutput(doOutput);
		connection.setIfModifiedSince(ifModifiedSince);
		connection.setUseCaches(useCaches);
	}

	private static class CacheStream extends OutputStream {

		private final OutputStream stream;

		private final OutputStream collector;

		public CacheStream(OutputStream stream, OutputStream collector) {
			this.stream = stream;
			this.collector = collector;
		}

		public void close() throws IOException {
			stream.close();
			collector.close();
		}

		public void flush() throws IOException {
			stream.flush();
			collector.flush();
		}

		public void write(byte[] b) throws IOException {
			stream.write(b);
			collector.write(b);
		}

		public void write(byte[] b, int off, int len) throws IOException {
			stream.write(b, off, len);
			collector.write(b, off, len);
		}

		public void write(int b) throws IOException {
			stream.write(b);
			collector.write(b);
		}

	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -