我已經用tomcat閥門解決了這個問題。閥檢查是否存在授權標頭,在這種情況下,標頭用作認證用戶的憑證,否則將發生正常的認證方法。
這裏是閥門的代碼:
package org.tastefuljava.tomcat;
import java.io.IOException;
import java.security.Principal;
import javax.servlet.ServletException;
import org.apache.catalina.Realm;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
public class AutoBasicValve extends ValveBase {
private static final String BASIC_PREFIX = "basic ";
private String encoding = "UTF-8";
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
@Override
public void invoke(Request request, Response response)
throws IOException, ServletException {
Principal principal = request.getUserPrincipal();
Realm realm = getContainer().getRealm();
if (principal != null) {
if (containerLog.isDebugEnabled()) {
containerLog.debug(
"Already authenticated as: " + principal.getName());
}
} else if (realm == null) {
if (containerLog.isDebugEnabled()) {
containerLog.debug("No realm configured");
}
} else {
String auth = request.getHeader("authorization");
if (auth != null) {
if (auth.toLowerCase().startsWith(BASIC_PREFIX)) {
auth = auth.substring(BASIC_PREFIX.length());
byte[] bytes = Base64.decode(auth);
auth = new String(bytes, encoding);
int ix = auth.indexOf(':');
if (ix >= 0) {
String username = auth.substring(0, ix);
String password = auth.substring(ix+1);
principal = realm.authenticate(username, password);
if (principal == null) {
containerLog.warn(
"Could not authenticate " + username);
} else {
containerLog.info(
"Authenticated as " + principal.getName());
request.setAuthType("BASIC");
request.setUserPrincipal(principal);
}
}
}
}
}
getNext().invoke(request, response);
}
}
您可以通過在你的tomcat安裝在server.xml文件中添加<閥門>標籤使用的閥門,或在META-INF /上下文。您Web應用程序的XML文件:
該項目在GitHub上:https://github.com/robbyn/mydsrealm
謝謝。我已經認爲這是不可能的。所以我認爲最好的選擇是爲web服務實現自定義身份驗證... – hage 2011-05-27 10:51:03