【问题标题】:@ModelAttribute is not working with spring security@ModelAttribute 不适用于 Spring Security
【发布时间】:2015-11-03 18:47:27
【问题描述】:

我试图在登录失败时重定向登录页面上输入的用户名,但在我的控制器中,从“@ModelAttribute("user")”检索到的用户的用户名为空。当我不使用弹簧安全时,这是可行的。

我假设表单实际上首先发布到 Spring Security,然后它被重定向到控制器,因此输入的信息在 Spring Security 之间丢失。

如何在不将用户发送到链接参数的情况下检索用户?

PS:我尝试为“/loginFailed”创建一个控制器,并在登录失败时将其发送到那里,并在该控制器上使用 method = RequestMethod.POST。

登录控制器

@RequestMapping(value = "/login", method = RequestMethod.GET)
    public String listPersons(@ModelAttribute("user") User u, @RequestParam(required = false) String authfailed, String logout,
            String denied, Model model) {
        model.addAttribute("user", u);
        String message = "";
        if (authfailed != null) {
            message = "Invalid username or password, try again !";
        } else if (logout != null) {
            message = "Logged Out successfully, login again to continue !";
        } else if (denied != null) {
            message = "Access denied for this user !";
        }
        model.addAttribute("error", message);
        return "login";
    }

login.jsp

<c:url var="trylogin" value="/j_spring_security_check" ></c:url>
<c:url var="register" value="/register" ></c:url>

<div id="login-box">
    <form:form action="" modelAttribute="user" method="POST">
        <table>
            <tr>
                <td> <form:label path="username"> <spring:message text="Username: "/> </form:label> </td>
                <td> <form:input path="username" /> </td> 
            </tr>
            <tr>
                <td> <form:label path="password"> <spring:message text="Password: "/> </form:label> </td>
                <td> <form:password path="password" /> </td> 
            </tr>
            <tr>
                <td> <input type="submit" value="<spring:message text="Login"/>"
                                    onclick="document.getElementById('user').setAttribute('action', '${trylogin}')"/> </td>
                <td> <input type="submit" value="<spring:message text="Register"/>"
                                    onclick="document.getElementById('user').setAttribute('action', '${register}')"/> </td>
            </tr>
        </table>
    </form:form>
    <c:if test="${not empty error}">
        <div class="error">${error}</div>
    </c:if>
</div>

编辑(解决方案):

谢谢@James,创建一个 failureHandler 是可行的方法,但是您的解决方案不能正常工作,因为即使我有“authentication-failure-url =”,您似乎在 failureHandler bean 中也需要“p:defaultFailureUrl” /login?authfailed"" 在表单登录中

<bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
    p:useForward="true"
    p:defaultFailureUrl="/login"/>

之后我不得不为 /login 添加另一个函数,因为 p:defaultFailureUrl="/login?authFailed" 只会将它作为 /login 发送,并且浏览器上的链接保持为 "/j_spring_security_check" 我不能'不明白为什么。

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginFail(@ModelAttribute("user") User u, @RequestParam(required = false) String authfailed, RedirectAttributes redirectAttrs) {
    redirectAttrs.addFlashAttribute("user", u);
    redirectAttrs.addFlashAttribute("error", "Invalid username or password, try again !");
    return "redirect:/login";
}

【问题讨论】:

    标签: java spring jsp spring-mvc spring-security


    【解决方案1】:

    您应该使用 AuthenticationFailureHandler。出于您的目的,声明 Spring SimpleUrlAuthenticationFailureHandler 类的 bean 并指定将请求转发到目标 URL 而不是配置中的默认重定向行为就足够了。这样,您的登录控制器将可以访问包括用户名在内的原始请求。

    文档:http://docs.spring.io/autorepo/docs/spring-security/3.2.1.RELEASE/apidocs/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.html

    来源:https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.java

    <bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
        p:useForward="true"
    />
    

    然后在您的表单登录规范中:

    <security:form-login 
        ...
        authentication-failure-handler-ref="failureHandler"
        ...
    /> 
    

    【讨论】:

      【解决方案2】:

      这是错误的方法。登录页面控制器仅用于查看此页面。对于检查凭证,您需要创建服务,例如:

      @Service("adminDetailsServiceImpl")
      public class AdminDetailsServiceImpl implements UserDetailsService {
          @Autowired
          private SepAdminDao adminDao;
      
          @Override
          public UserDetails loadUserByUsername(String login) {
              SepAdmin admin;
      
              if (StringUtils.isBlank(login))
                  throw new UsernameNotFoundException("Admin not found!");
              admin = adminDao.findByEmail(login);
              return new org.springframework.security.core.userdetails.User(
                      admin.getEmail(),
                      admin.getPassword(),
                      getGrantedAuthorities(admin.getRole().getPermissionNames()));
          }
      
          private static List<GrantedAuthority> getGrantedAuthorities(String[] roles) {
              List<GrantedAuthority> authorities = new ArrayList<>();
              for (String role : roles)
                  authorities.add(new SimpleGrantedAuthority(role));
              return authorities;
          }
      }
      

      用 spring 分配这个服务(例如我查看我的简单安全配置):

      <?xml version="1.0" encoding="UTF-8"?>
      <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.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security.xsd">
          <beans:bean id="roleHierarchy" class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
              <beans:property name="hierarchy">
                  <beans:value>
                      <!--Admin-->
                      PERM_ROOT > PERM_CREATE_ADMINS
                      PERM_CREATE_ADMINS > PERM_DELETE_ADMINS
                      PERM_DELETE_ADMINS > PERM_EDIT_ADMINS
                      PERM_EDIT_ADMINS > PERM_VIEW_ADMINS
                      <!--Role-->
                      PERM_ROOT > PERM_CREATE_ROLES
                      PERM_CREATE_ROLES > PERM_DELETE_ROLES
                      PERM_DELETE_ROLES > PERM_EDIT_ROLES
                      PERM_EDIT_ROLES > PERM_VIEW_ROLES
                  </beans:value>
              </beans:property>
          </beans:bean>
          <beans:bean id="expressionHandler"
                      class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler">
              <beans:property name="roleHierarchy" ref="roleHierarchy"/>
          </beans:bean>
          <beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
              <beans:property name="decisionVoters">
                  <beans:list>
                      <beans:bean class="org.springframework.security.web.access.expression.WebExpressionVoter">
                          <beans:property name="expressionHandler" ref="expressionHandler"/>
                      </beans:bean>
                  </beans:list>
              </beans:property>
          </beans:bean>
          <beans:bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
              <beans:constructor-arg ref="roleHierarchy"/>
          </beans:bean>
          <beans:bean id="passwordEncoder"
                      class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
              <beans:constructor-arg value="10"/>
          </beans:bean>
          <http pattern="/resources/js/vendor/language" security="none"/>
          <http pattern="/favicon.ico" security="none"/>
          <http auto-config="true" use-expressions="true" access-denied-page="/403"
                access-decision-manager-ref="accessDecisionManager">
              <intercept-url pattern="/login" access="permitAll"/>
              <!--Admin-->
              <intercept-url pattern="/dashboard" access="hasRole('PERM_ROOT')"/>
              <intercept-url pattern="/admin/create_admin" access="hasRole('PERM_CREATE_ADMINS')"/>
              <intercept-url pattern="/admin/users/*/edit_admin" access="hasRole('PERM_EDIT_ADMINS')"/>
              <intercept-url pattern="/admin/users/*/view_admin" access="hasRole('PERM_VIEW_ADMINS')"/>
              <intercept-url pattern="/admin/users/*/delete_admin" access="hasRole('PERM_DELETE_ADMINS')"/>
              <!--Role-->
              <intercept-url pattern="/role/create_role" access="hasRole('PERM_CREATE_ROLES')"/>
              <intercept-url pattern="/role/*/edit_role" access="hasRole('PERM_EDIT_ROLES')"/>
              <intercept-url pattern="/role/*/view_role" access="hasRole('PERM_VIEW_ROLES')"/>
              <intercept-url pattern="/role/*/delete_role" access="hasRole('PERM_DELETE_ROLES')"/>
              <!--Route-->
              <form-login username-parameter="email"
                          password-parameter="password"
                          login-page="/login" default-target-url="/" authentication-failure-url="/login?failed"/>
              <logout logout-url="/logout" logout-success-url="/login"/>
          </http>
          <authentication-manager alias="authManager">
              <authentication-provider user-service-ref="adminDetailsServiceImpl">
                  <password-encoder ref="passwordEncoder"/>
              </authentication-provider>
          </authentication-manager>
      </beans:beans>
      

      然后当用户提交登录表单时,我们重定向到 /j_spring_security_check 使用我们的服务的地方,如果我们有登录异常,我们可以在登录 jsp 页面检查它:

      <!-- spring_exception -->
      <c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
          <p class="alert alert-danger alert-dismissable">
              <spring:message code="Error.Msg.Login"/>
          </p>
          <br/>
      </c:if>
      

      如果成功,我们将重定向到默认目标 url,在我的例子中 - 到 root。

       <form-login username-parameter="email"
               password-parameter="password"
               login-page="/login" default-target-url="/" authentication-failure-url="/login?failed"/>
      

      这就是为什么浏览器上的链接保持为“/j_spring_security_check”的原因。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-25
        • 2015-10-02
        • 1970-01-01
        • 2014-11-29
        • 2020-12-02
        • 2016-04-16
        • 2017-08-07
        • 2016-03-13
        相关资源
        最近更新 更多