我使用Spring、Security和Apache Tiles,我有以下问题:
我希望unauthenticated用户登陆我的网站(即www.mywebsite.com/)的主页网址,在那里将向他们播放一个登录表单,以便他们可以从那里进行身份验证。
然后,一旦对用户进行了身份验证,我希望完全不同的页面内容能够在网站的主页URL (仍然是www.mywebsite.com/)上向他们显示,可能使用另一个模板/jsp。
我想要实现的基本上是,能够根据用户是否经过身份验证来显示相同URL的不同内容--所有这些都使用security和Spring。
我研究过Security,但未能找到上述问题的解决方案。其他人也遇到了类似的问题(参见:Spring安全性-根据用户角色提供不同内容的相同页面)
能否请任何人就如何实现这一问题提供指导或建议?
发布于 2012-09-26 11:41:39
我可以想到的一个解决方案是在您的MVC控制器中签入来自请求的用户主体,如果通过身份验证/拥有角色返回一个ModelAndView,否则返回另一个:
@Controller
public class MyController{
public ModelAndView doSomething(HttpServletRequest request, HttpServletResponse response){
if(request.getUserPrincipal() != null && request.isUserInRole("someRole"){
return new ModelAndView("view1");
}
else {
return new ModelAndView("view2");
}
}
}发布于 2013-06-25 17:10:10
我可以想出几种方法来实现你想要的。
首先,您可以使用Security在视图模板中有条件地呈现内容,这取决于用户是否正确的身份验证。关于Security的更多信息是这里。粗略地说,这将使视图模板看起来类似于:
if(user is authenticated)
render content for authenticated user
else
render log-in form然而,这感觉有点直截了当,因为您的Controller总是在创建模型,而不管您的用户是否经过了正确的身份验证。当您想要显示登录表单时,您还需要在视图模板中使用此逻辑。
另一种方法是创建一个HandlerInterceptor实现,将所有请求转发给负责呈现登录页面的Controller,直到用户完全通过身份验证为止。您可以使用您的preHandle()方法来执行以下操作:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyHandlerInterceptor implements HandlerInterceptor
{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
SecurityContext sc = SecurityContextHolder.getContext();
boolean userAuthenticated = true;
/* Some logic in here to determine if the user is correctly authenticated */
if(!userAuthenticated)
{
request.getRequestDispatcher("/login").forward(request, response);
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
{
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
{
}}然后,您可以配置Spring将您的HandlerInterceptor实现映射到您需要此功能的URL上。这就避免了在所有控制器上重复逻辑,而且很容易测试。
发布于 2012-09-26 12:55:44
你可以试着用
<security:authorize access=”isAnonymous()”>
not authenticated page
</security:authorize>
<security:authorize access=”isAuthenticated()”>
authenticated page
</security:authorize>或者,您可以将控制器中的“重定向: page_for_not_auth”作为视图名返回,以便将响应重定向到处理非自动处理请求的另一个控制器/方法。
https://stackoverflow.com/questions/12600425
复制相似问题