星期二, 十月 12, 2004

通过 Servlet 代码实现 Basic 认证

无需设置,通过标准的 Servlet 代码即可实现 Basic 认证。代码示例(比如在servlet的doGet方法中):

if (authenticate(req))
{
// 认证通过
}
else
{
//***We weren't sent a valid username/password in the header, so ask for one***
res.setHeader("WWW-Authenticate","Basic realm=\"Authorisation test servlet\"");
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "");
}

上面的authenticate()是判断是否已通过Basic认证的函数,主要代码如下(Base64的Java代码很常见的,此处从略):

private boolean authenticate(HttpServletRequest req)
{
String authhead=req.getHeader("Authorization");
if(authhead!=null)
{
//*****Decode the authorisation String*****
String usernpass=Base64.decode(authhead.substring(6));
//*****Split the username from the password*****
String user=usernpass.substring(0,usernpass.indexOf(":"));
String password=usernpass.substring(usernpass.indexOf(":")+1);

if (user.equals("user") && password.equals("pass"))
return true;
}
return false;
}

0 Comments:

发表评论

Links to this post:

创建链接

<< Home