【发布时间】:2015-01-16 20:48:21
【问题描述】:
我正在编写一个 Spring 应用程序,该应用程序要求用户登录才能访问已使用 Spring 安全性保护的页面。当用户尝试访问安全页面时,他们会被要求登录。如果登录成功,用户应该被直接重定向到安全页面,否则登录页面应该重新显示错误消息。目前不成功的场景有效,但如果用户正确登录,登录页面仍然会重新显示,尽管没有错误消息。
这里是相关的Java代码和Spring配置:
用户凭据控制器:
//Methods omitted above.
@RequestMapping(value="/login", method = RequestMethod.GET)
public String login(Model model){
System.out.println("In login() method");
model.addAttribute("credentials", new User());
return "login";
}
@RequestMapping(value="/checkcredentials", method = RequestMethod.POST)
public String checkCredentials(@ModelAttribute ("credentials") User user, Model model, HttpServletResponse response){
if(userService.getUser(user)){
//I am trying to redirect the user here in the event of a successful log in. Does not work at present.
return "redirect:/addincident";
}
else{
model.addAttribute("message", "Username and/or password is/are not valid");
//This works at the moment.
return "login";
}
}
spring-security.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true">
<intercept-url pattern="/addincident" access="ROLE_USER, ROLE_ADMIN"/>
<intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<form-login login-page="/login"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="daj" password="123" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="eoj" password="123" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
我目前的想法是这是一个安全问题。这是因为以前我使用 Spring 的默认登录页面,当我使用基于 XML 的用户时它工作得很好。但是现在我将用户保存在数据库中,并且我有自己的登录页面,并且导航不再按我期望的方式工作。
编辑:这是 addIncident 方法。当我使用默认的 Spring 登录表单时,它会正确加载。
GeneralIncidentController:
//Methods omitted above.
@RequestMapping(value = "/addincident", method = RequestMethod.GET)
public String addIncident(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model){
model.addAttribute("message", "Spring 3 MVC Hello World");
model.addAttribute("name", name);
model.addAttribute("details", new GeneralIncident()); //Need this to populate bean with submitted data for validation.
return "myform";
}
【问题讨论】:
-
我不确定这是否适用于我的情况?看起来该配置用于使用默认登录页面。我有名为 authentication-manager 的标签,但没有 bean。
标签: java spring security spring-mvc spring-security