2016-01-13 3 views
1

Я пытаюсь реализовать аутентификацию с использованием весенней безопасности.Ошибка аутентификации пользователя Spring Security

Я не могу понять, что я делаю неправильно.

web.xml имеет фильтр безопасности:

<!-- Spring Security --> 
<filter> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter> 

<filter-mapping> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

весна-security.xml имеет определенные перехватывает URL-адрес и менеджер аутентификации:

<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-4.1.xsd 
    http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security-4.0.xsd"> 

    <!-- enable use-expressions --> 
    <http auto-config="true" use-expressions="true"> 
     <intercept-url pattern="/" access="permitAll" /> 
     <intercept-url pattern="/logout**" access="permitAll" /> 

     <!-- Incoming Product --> 
     <intercept-url pattern="/incomingProduct**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 

     <!-- Maintanence pages --> 
     <intercept-url pattern="/depotUser**" access="hasRole('Administrator') and hasRole('Local_Administrator')" /> 
     <intercept-url pattern="/product**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 
     <intercept-url pattern="/productOwner**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 
     <intercept-url pattern="/storageTank**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 

     <intercept-url pattern="/admin**" access="hasRole('Administrator')" /> 

     <!-- access denied page --> 
     <access-denied-handler error-page="/error/403" /> 
     <form-login 
      login-page="/" 
      default-target-url="/" 
      authentication-failure-url="/Access_Denied" 
      username-parameter="username" 
      password-parameter="password" /> 
     <logout logout-success-url="/logout" /> 
     <!-- enable csrf protection --> 
     <csrf /> 
    </http> 

    <authentication-manager> 
     <authentication-provider user-service-ref="userSecurityService" /> 
    </authentication-manager> 

    <beans:bean id="userSecurityService" class="com.tms.securityServices.UserSecurityService" > 
     <beans:property name="depotUserDao" ref="depotUserDao" /> 
    </beans:bean> 

</beans:beans> 

UserSecurityService реализует UserDetailsService. В соответствии с конфигурацией в spring-security.xml это должно быть вызвано для аутентификации запроса на вход и вставки пользователя в сеанс. (! Пожалуйста, поправьте меня, если я ошибаюсь)

@Transactional 
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 
{ 
    DepotUser user = depotUserDao.findByUserName(username); 
    System.out.println("User : " + user); 
    if (user == null) 
    { 
     System.out.println("User not found"); 
     throw new UsernameNotFoundException("Username not found"); 
    } 
    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.isActive(), true, true, true, 
      getGrantedAuthorities(user)); 
} 

private List<GrantedAuthority> getGrantedAuthorities(DepotUser user) 
{ 
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 

    for (DepotUserRole userProfile : user.getUserRole()) 
    { 
     System.out.println("UserProfile : " + userProfile); 
     authorities.add(new SimpleGrantedAuthority("ROLE_" + userProfile.getRole())); 
    } 

    System.out.print("authorities :" + authorities); 
    return authorities; 
} 

Войти контроллер обработки запроса:

@RequestMapping(value = { "/loginRequest" }, method = RequestMethod.POST) 
public String loginRequest(@RequestParam String username, @RequestParam String password, HttpServletRequest request, HttpServletResponse response) 
     { 
      DepotUser user = depotUserManager.getUserByUsernamePassword(username, password); 

      if (user != null) 
      { 
       request.setAttribute("firstName", user.getFirstName()); 
       request.setAttribute("lastName", user.getLastName()); 
       request.setAttribute("username", user.getUsername()); 
       request.setAttribute("userRoles", user.getUserRole()); 
       return "homePage"; 
      } 

Что происходит, когда я войти в систему пользователь получает вход с анонимным пользователем.

Аутентификация не запускается, поскольку я не получаю точки разрыва в UserSecurityService. Также в контроллере весны, который обрабатывает запрос.

Может ли кто-нибудь помочь мне?

Любая помощь приветствуется.

Спасибо,

ответ

1

Там более чем одной детали, которая не кажется правильным

В конфигурации, в разделе входа:

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

, указав login-page="/", это означает, что Запрос POST с данными формы для аутентификации должен быть указан на URL-адресе "/", но вы пытаетесь выполнить проверку подлинности на "/loginRequest" в контроллере.

Во-вторых, аутентификация обработки не является чем-то, что вам нужно управлять самостоятельно в контроллере, весенняя безопасность делает это автоматически для вас, просто отправьте форму на URL-адрес, указанный в конфигурации.

Update:

Что касается формы входа в систему, вы должны убедиться, что следующие вещи:

  • URL действия формы соответствует параметру login-page в конфигурации, которая is "/"
  • имя свойства поля ввода для имени пользователя должно соответствовать username-parameter в конфигурации "username" в вашем случае
  • имени свойство поля ввода пароля должен соответствовать password-parameter в конфигурации, "password" в вашем случае.

Вы должны также удалить modelAttribute="loginUser"

+0

Благодаря @saljuama я попытался согласно вам предложение, изменение <форма входа-входа-страницу = "/ loginRequest". Все так же подействует. –

+0

Часть в контроллере предназначена только для целей тестирования. –

+0

Да, это тестирование может препятствовать весенней безопасности делать то, что предлагается делать :). Кроме того, что сказал @JacekWcislo в своем ответе, как выглядит ваша форма входа? можете ли вы добавить этот код к своему вопросу? – saljuama

0

Как ваш Логиниться выглядеть? У вас есть

(thymeleaf)

<form th:action="@{/j_spring_security_check}" method="post"> 

(JSP)

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

один из них? Можете ли вы показать свое мнение?

+0

моя форма для входа '

' в соответствии с запросом @saljuama @JacekWcislo –

+0

Можете ли вы рассказать о том, что такое j_spring_security_check? –

+0

Это неправильно; вы не запускаете пружинные фильтры безопасности. Прочтите это: https://docs.spring.io/spring-security/site/docs/3.0.x/reference/core-web-filters.html. Измените свое действие, чтобы соответствовать моему сообщению, и все должно быть в порядке. – wcislo

0

@JacekWcislo, @saljuama У меня есть login-page="/", потому что моя целевая страница по умолчанию - это страница входа. Я добавляю в качестве ответа, поскольку хочу показать обновленный код.

после прочтения предложений и ссылки, представленные я обновил свой 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-4.1.xsd 
    http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security-4.0.xsd"> 

    <!-- enable use-expressions --> 
    <http auto-config="true" use-expressions="true" entry-point-ref="authenticationEntryPoint"> 
     <intercept-url pattern="/" access="permitAll" /> 
     <intercept-url pattern="/logout**" access="permitAll" /> 

     <!-- Incoming Product --> 
     <intercept-url pattern="/incomingProduct**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 

     <!-- Maintanence pages --> 
     <intercept-url pattern="/depotUser**" access="hasRole('Administrator') and hasRole('Local_Administrator')" /> 
     <intercept-url pattern="/product**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 
     <intercept-url pattern="/productOwner**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 
     <intercept-url pattern="/storageTank**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 

     <intercept-url pattern="/admin**" access="hasRole('Administrator')" /> 

     <!-- access denied page --> 
     <access-denied-handler error-page="/error/403" /> 
     <form-login 
      login-page="/" 
      default-target-url="/homePage" 
      authentication-failure-url="/loginPage?invalidLogin=Yes" 
      username-parameter="username" 
      password-parameter="password" 

      /> 
     <logout logout-success-url="/logout" /> 
     <!-- enable csrf protection --> 
     <csrf /> 

     <custom-filter before="FORM_LOGIN_FILTER" ref="authenticationFilter"/> 
    </http> 

    <beans:bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"> 
     <beans:property name="authenticationManager" ref="authenticationManager" /> 
    </beans:bean> 

    <beans:bean id="authenticationEntryPoint" class= "org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> 
     <beans:constructor-arg value="/j_spring_security_check"/> 
    </beans:bean> 

    <authentication-manager alias="authenticationManager"> 
     <authentication-provider user-service-ref="userSecurityService" /> 
    </authentication-manager> 

    <beans:bean id="userSecurityService" class="com.tms.securityServices.UserSecurityService" > 
     <beans:property name="depotUserDao" ref="depotUserDao" /> 
    </beans:bean> 

</beans:beans> 

любой мой Логин JSP является

<form id="loginForm" method="post" modelAttribute="loginUser" action="<c:url value='j_spring_security_check' />"> 

его дает мне ошибку 404. Я предполагаю, что мне придется сопоставить весенний адрес безопасности.

у меня есть это в моей

AuthenticationEntryPoint

там где-нибудь еще я буду наносить его на карту?

+0

в будущем, вместо того, чтобы добавлять новый ответ, лучше отредактировать свой оригинальный пост и включить в него новую информацию, это упростит для всех :) – saljuama

0

Я смог решить эту проблему, добавив соответствующие фильтры, точку входа и обработчики.

код:

<!-- enable use-expressions --> 
<http auto-config="true" use-expressions="true" entry-point-ref="authenticationEntryPoint"> 

    <!-- Dashboard & resources --> 
    <intercept-url pattern="/" access="permitAll" /> 
    <intercept-url pattern="/loginRequest**" access="permitAll" /> 
    <intercept-url pattern="/logout**" access="permitAll" /> 
    <intercept-url pattern="/dashboard**" access="permitAll" /> 
    <intercept-url pattern="/**/resources**" access="permitAll" /> 

    <!-- Incoming Product --> 
    <intercept-url pattern="/incomingProduct**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 

    <!-- Maintanence pages --> 
    <intercept-url pattern="/depotUser**" access="hasRole('Administrator') and hasRole('Local_Administrator')" /> 
    <intercept-url pattern="/product**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 
    <intercept-url pattern="/productOwner**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 
    <intercept-url pattern="/storageTank**" access="hasRole('Administrator') and hasRole('Local_Administrator') and hasRole('Supervisor') and hasRole('Manager')" /> 

    <intercept-url pattern="/admin**" access="hasRole('Administrator')" /> 

    <!-- access denied page --> 
    <access-denied-handler error-page="/error/403" /> 
    <form-login 
     login-page="/" 
     login-processing-url="/loginRequest" 
     default-target-url="/dashboard/home" 
     authentication-failure-url="/loginPage?invalidLogin=Yes" 
     username-parameter="username" 
     password-parameter="password" 
     /> 
    <logout logout-success-url="/logout" /> 
    <!-- enable csrf protection --> 
    <csrf /> 

    <custom-filter before="FORM_LOGIN_FILTER" ref="authenticationFilter"/> 
</http> 

<beans:bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"> 
    <beans:property name="authenticationManager" ref="authenticationManager" /> 
    <beans:property name="authenticationSuccessHandler" ref="authenticationSuccessHandler" /> 
</beans:bean> 

<beans:bean id="authenticationEntryPoint" class= "org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> 
    <beans:constructor-arg value="/loginRequest"/> 
</beans:bean> 

<beans:bean id="authenticationSuccessHandler" 
    class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> 
    <beans:property name="defaultTargetUrl" value="/dashboard/home" /> 
</beans:bean> 

<authentication-manager alias="authenticationManager"> 
    <authentication-provider user-service-ref="userSecurityService" /> 
</authentication-manager> 
Смежные вопросы