1

如何在具有 Shiro 安全性的 Spring MVC 应用程序中实现以下场景:

如果用户未通过身份验证并请求页面,Shiro 应重定向到登录页面。用户登录成功,Shiro 重定向到之前请求的页面而不是successUrl URL

登录部分在我的应用程序中工作正常。以下是我现有代码的片段

<!-- Shiro filter -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/login" />
        <property name="successUrl" value="/dashboard" />
        <property name="unauthorizedUrl" value="/error" />
        <property name="filterChainDefinitions">
            <value> 
                <!-- !!! Order matters !!! -->
                /authenticate = anon
                /login = anon
                /logout = anon
                /error = anon
                /static/** = anon
                /** = authc
            </value>
        </property>
    </bean>
4

1 回答 1

2

在登录控制器中:

public String doLogin(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam(required = true) String username,
        @RequestParam(required = true) String password,
        @RequestParam(required = false, defaultValue = "false") boolean rememberMe,
        Model model) {
    Subject currentUser = SecurityUtils.getSubject();

    ...

    if (currentUser.isAuthenticated()) {
        String fallbackUrl = "redirect:/";
        try {
            // redirect to previously requested page
            WebUtils.redirectToSavedRequest(request, response, fallbackUrl);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            return fallbackUrl;
        }
        // return null to prevent spring render another page
        return null;
    } else {
        session.setAttribute("loginFailCount", ++loginFailCount);
    }
    return "login";
}
于 2012-12-19T15:22:25.607 回答