我正在尝试将apache shiro用于我的项目,因为我必须在我的项目中创建基于角色的机制。我创建了一个包含以下配置的演示项目......
我在我的项目中创建了以下文件 -
的index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Shiro Web Test</title>
</head>
<body>
<h1>This is a test for Shiro Web Framework</h1>
<a href = "success.jsp">Click Here!</a>
</body>
</html>
的login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Shiro Web Test : Login Page</title>
</head>
<body>
<%! String errorMessage = null; %>
<%
errorMessage = (String) request.getAttribute("shiroLoginFailure");
if (errorMessage != null) { %>
<font color="red">Invalid Login: ${errorMessage}</font><br/>
<font color="black"><h3>Enter login information...</h3></font>
<% } else { %>
<font color="black"><h3>Enter login information...</h3></font>
<% } %>
<form action="loginTest.do" method="POST">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" placeholder="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="password" /></td>
</tr>
</table>
<input type="checkbox" value="true" name="rememberMe" />Remember Me?<br />
<input type="submit" value="Sign In" />
</form>
</body>
</html>
的success.jsp
的 denied.jsp
的 logout.jsp
的 showUser.jsp
我的 shiro.ini 配置如下 -
# =======================
# Shiro INI configuration
# =======================
[main]
authc = org.apache.shiro.web.filter.authc.FormAuthenticationFilter
roles = org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
authc.loginUrl = /login.jsp
authc.failureKeyAttribute = shiroLoginFailure
roles.unauthorizedUrl = /denied.jsp
[users]
admin = password, ROLE_ADMIN
member = password, ROLE_MEMBER
[roles]
ROLE_ADMIN = *
[urls]
/success.jsp = authc, roles[ROLE_MEMBER]
/secret.jsp = roles[ROLE_ADMIN]
我使用servlet LoginTestServlet.java 在身份验证成功/失败后调度到 login.jsp 页面或 success.jsp -
public class LoginTestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
generateResponse(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
generateResponse(request, response);
}
protected void generateResponse(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
UserCredentials user = new UserCredentials();
user.setUserName(request.getParameter("username"));
user.setPassword(request.getParameter("password"));
if (user.getUserName() != null && user.getPassword() != null) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
try {
currentUser.login(token);
Session session = currentUser.getSession();
session.setAttribute("user", user.getUserName());
} catch (UnknownAccountException uae) {
request.setAttribute("shiroLoginFailure", uae.getMessage());
System.err.println("Exception type: " + uae.getClass().getName());
System.err.println("Error due to: " + uae.getMessage());
} catch (IncorrectCredentialsException iae) {
request.setAttribute("shiroLoginFailure", iae.getMessage());
System.err.println("Exception type: " + iae.getClass().getName());
System.err.println("Error due to: " + iae.getMessage());
} catch (LockedAccountException lae) {
request.setAttribute("shiroLoginFailure", lae.getMessage());
System.err.println("Exception type: " + lae.getClass().getName());
System.err.println("Error due to: " + lae.getMessage());
} catch (AuthenticationException ae) {
request.setAttribute("shiroLoginFailure", ae.getMessage());
System.err.println("Exception type: " + ae.getClass().getName());
System.err.println("Error due to: " + ae.getMessage());
} catch (Exception e) {
request.setAttribute("shiroLoginFailure", e.getMessage());
System.err.println("Exception type: " + e.getClass().getName());
System.err.println("Error due to: " + e.getMessage());
}
RequestDispatcher view = null;
if (currentUser.isAuthenticated() && currentUser.hasRole("ROLE_MEMBER")) {
view = request.getRequestDispatcher("success.jsp");
view.forward(request, response);
} else if (currentUser.isAuthenticated() && currentUser.hasRole("ROLE_ADMIN")) {
view = request.getRequestDispatcher("secret.jsp");
view.forward(request, response);
} else {
view = request.getRequestDispatcher("login.jsp");
view.forward(request, response);
}
}
}//end of generateResponse()
}//end of class
我正在使用TOMCAT 6.0。
我的问题是 -
另外,有没有办法在shiro中为每个资源创建自定义权限?如果是,那怎么样。如果有任何链接,我将不胜感激。
谢谢大家。
答案 0 :(得分:0)
我想知道为什么你决定在servlet中处理身份验证,而不是像指南中已经定义的那样using the pre-built filter(除此之外,你似乎正在重新加载配置并创建一个新的{ {1}}每次请求......)。过滤器应该为您处理#1中的详细信息。
如果你坚持使用servlet,你需要在会话中添加一个值,或者作为login.jsp请求的参数,告诉它在成功验证后应该在哪里重定向用户,并在读取该参数后用户已通过身份验证。
关于#2,您只需在成功验证后转发SecurityManager
。您不是1)明确检查用户的角色或允许框架为您执行此操作。同样,切换到过滤器应该为您解决此问题。