hag*_*age 17 java login web-applications
我有一个Java Web应用程序,它有一个用于用户交互的网站.要对用户进行身份验证,我通过web.xml配置了应用程序以使用基于FORM的身份验证.用户被转发到登录页面,到目前为止一切都很好.
现在我们正在为这个通过RESTful Web服务访问应用程序的Web应用程序开发一个桌面客户端(在C#中).我在与网站相同的Web应用程序中实现了这些服务,当然也应该对Web服务的调用者进行身份验证.但是现在我面临的问题是,无论何时我调用Web服务,服务器都会返回登录页面的HTML作为响应.
我认为能够为我的REST服务servlet使用另一个login-config(它可能会使用BASIC身份验证)会很酷.
谷歌并没有带来多少,但我无法相信我是第一个处于这种状况的人.所以我想听听你的想法和解决方案.
任何提示都表示赞赏.
我已经用一个 tomcat 阀门解决了这个问题。Valve 会检查 Authorization 标头是否存在,在这种情况下,标头用作验证用户的凭据,否则,将使用正常的身份验证方法。
这是阀门的代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过在 tomcat 安装的 server.xml 文件或 WebApp 的 META-INF/context.xml 文件中添加 <Valve> 标记来使用该阀:
项目在github上:https : //github.com/robbyn/mydsrealm
| 归档时间: |
|
| 查看次数: |
10798 次 |
| 最近记录: |