【问题标题】:spring security 3.1 allow user to sign and proceed to restricted pagesspring security 3.1 允许用户签名并继续访问受限页面
【发布时间】:2013-06-05 15:44:03
【问题描述】:

我正在使用 Spring Security 3.1 进行身份验证,并且登录工作正常。当用户注册时,我希望用户无需登录即可继续访问受限页面。

stackoverflow 上有几个类似的问题,答案略有不同,我已经尝试过这些,但似乎没有什么对我有用。这是我的安全配置:

<http pattern="/resources/**" security="none" />       
<http pattern="/login" security="none" /> 
<http pattern="/user/forgotPassword" security="none" />
<http pattern="/user/createAccount" security="none" />
<http>
    <intercept-url pattern="/**" access="ROLE_USER" /> 
    <form-login login-page="/login" default-target-url="/defaultUrl"
        always-use-default-target="true"
        authentication-failure-url="/loginfailed" />
</http>

这是我的代码(在创建用户并将其添加到数据库之后):

UsernamePasswordAuthenticationToken upaToken = new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword());
request.getSession();
upaToken.setDetails(new WebAuthenticationDetails(request));
Authentication auth = authenticationManager.authenticate(upaToken);
SecurityContextHolder.getContext().setAuthentication(upaToken);

return "redirect:<restricted-page>";

显示登录页面,而不是重定向到受限页面。我错过了什么?

我还想避免调用来验证用户。这似乎没有必要,因为用户刚刚注册。但删除它似乎并没有改变任何东西。

【问题讨论】:

  • 您的注册控制器(包含显示的代码)映射到哪个 URL?
  • 映射到/user/createAccount。

标签: authentication spring-security


【解决方案1】:

问题的根本原因是由于以下规则,您的 /user/createAccount URL 未被 Spring 安全过滤器覆盖:

<http pattern="/user/createAccount" security="none" />

其中一个 Spring Security 过滤器可以在请求之间自动保留 SecurityContext。与其进行低级会话操作,不如为 /user/createAccount 启用过滤器链并允许任何用户访问此 URL。您可以使用以下语法:

<http>
    <intercept-url pattern="/user/createAccount" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/**" access="ROLE_USER" /> 
    ...
</http>

一般来说,最好为每个 URL 保留有效的 spring 安全过滤器链,并且不要手动重写它们的功能。

【讨论】:

    【解决方案2】:

    您需要将上下文保存到会话中

    HttpSession session = request.getSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
    

    如果没有设置JSESSIONID cookie,您需要将其设置为会话 ID

    【讨论】:

    • 谢谢!在会话中保存上下文是缺少的。不必对 JSESSIONID 做任何事情。我想我无法避免身份验证部分。在 SO 的其他地方,据说在 Spring SecurityContext 中保存 UsernamePasswordAuthenticationToken 就足够了,但似乎还不够。
    • 它会针对当前请求,然后当下一个请求到来时,spring security会在会话中寻找经过身份验证的上下文,如果没有找到将重定向回登录页面
    猜你喜欢
    • 2015-10-09
    • 2013-11-25
    • 1970-01-01
    • 2014-09-02
    • 2011-01-01
    • 2017-12-21
    • 2015-03-12
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多