2014-09-02 87 views
1

我有一个网站部分(所有在/secure的URL下),我试图用Spring Security 3.2.5来保证。我使用下面的XML配置:Spring Security with XML configuration does not authenticate user

<http use-expressions="true"> 
    <intercept-url pattern="/secure/login" access="permitAll" /> 
    <intercept-url pattern="/secure/**" access="isAuthenticated()" /> 
    <form-login default-target-url="/secure/home" always-use-default-target="true" login-page="/secure/login" /> 
</http> 

<authentication-manager> 
    <authentication-provider> 
     <user-service> 
      <user name="user" password="password" authorities="ROLE_SECURE" /> 
     </user-service> 
    </authentication-provider> 
</authentication-manager> 

我试图使用我有这个控制器定制登录表单:

@Controller 
@RequestMapping(value = "/secure") 
public class LoginController { 
    @RequestMapping(value = "/login", method = RequestMethod.GET) 
    public String getLogin() { 
     return "secure/login"; 
    } 

    @RequestMapping(value = "/home", method = RequestMethod.GET) 
    public String getHome() { 
     return "secure/home"; 
    } 
} 

和验证码登录页面内:

<form method="POST" action="<c:url value="/secure/login" />"> 
    username: <input type="text" name="username" /><br/> 
    password: <input type="password" name="password" /><br/> 
    <input type="submit" value="Login" /> 
</form> 

我必须使用web.xmlContextLoaderListenerspringSecurityFilterChain委托代理过滤器在加载的安全上下文也设置。

当我尝试访问/secure网址时,我重定向到/secure/login,我的控制器在getLogin方法中调用,我看到了我的登录页面。没关系。

现在我的问题:无论我在登录表单提交被直接发送到LoginController,我得到一个异常说POST是不支持 方法,这是有道理的,因为在控制器中没有POST处理程序。

如果我在控制器中添加一个方法是这样的:

@RequestMapping(value = "/login", method = RequestMethod.POST) 
public String postLogin() { 
    return "redirect:/secure/home"; 
} 

我不再得到的错误,但我postLogin方法被调用至极把我送到/secure/home未经验证,然后重定向我/secure/login和我回到原点。

我不知道我在做什么错。我在网上看到的所有示例都是Java配置,我不愿意使用,并且所有工作流都在应用程序上下文中,而不是在一些额外的URL路径下(在我的示例中为/secure)。

我错过了什么?

回答

1

表的文档(http://docs.spring.io/spring-security/site/docs/3.0.x/reference/appendix-namespace.html):

默认目标网址

映射到UsernamePasswordAuthenticationFilter的defaultTargetUrl属性的值。如果未设置,则默认值为“/”(应用程序根目录)。如果用户在尝试访问受保护的资源时没有被要求登录,并将其带到最初请求的URL,则用户将在登录后进入该URL。

你必须提交表格j_spring_security_check

<form name='loginForm' 
      action="<c:url value='j_spring_security_check' />" method='POST'> 

这将通过Spring Security的处理,并检查将根据您的配置用户和通。 看到这个例子http://www.mkyong.com/spring-security/spring-security-form-login-example/

编辑:j_security_check也应该被支持。

相关问题