使用Apache Shiro配置无法获得正确的结果



我试图使用apache shiro到我的项目,因为我必须创建一个基于角色的机制到我的项目。我用以下配置创建了一个演示项目…

我在我的项目中创建了以下文件-

<<p> index . jsp/strong>
<%@ 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 logtestservlet .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.

我的问题是-

  1. 每当我试图在login.jsp页面上输入凭据时,它会自动将我带到我输入凭据的相应页面。例如,如果我在点击success.jsp后尝试输入ROLE_MEMBER凭据,它会将我带到success.jsp页面。但是,如果我尝试在点击相同的success.jsp后进入ROLE_ADMIN,它会自动将我带到secret.jsp,按照编写的servlet代码,而不是转到denied.jsp.
  2. 如何使一个通用的代码没有写一个单独的servlet为每个资源显示登录成功或拒绝页面?

还有,有没有办法在shiro中为每个资源创建自定义权限?如果是,那么怎么做呢?如果有任何链接,我将不胜感激。

谢谢。

我想知道为什么您决定在servlet内部处理身份验证,而不是使用指南中已经定义的预构建过滤器(除其他事项外,您似乎正在重新加载配置并在每个请求上创建新的SecurityManager…)。过滤器应该为您处理#1中的细节。

如果坚持使用servlet,则需要在会话中添加一个值,或者作为login.jsp请求的参数添加一个值,该值告诉它在身份验证成功后应该将用户重定向到哪里,并在用户身份验证完成后读取该参数。

关于#2,您只是在成功验证后转发success.jsp。您既没有1)显式地检查用户的角色,也没有允许框架为您这样做。同样,切换到过滤器应该可以为您解决这个问题。

相关内容

  • 没有找到相关文章

最新更新