Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Java [игнор отключен] [закрыт для гостей] / Spring Security Bad credentials / 3 сообщений из 3, страница 1 из 1
12.02.2018, 10:16
    #39600426
Щиче
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Spring Security Bad credentials
Есть конфигурация:

security.xml:
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
<?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-4.3.xsd
                    http://www.springframework.org/schema/security
                    http://www.springframework.org/schema/security/spring-security-4.2.xsd">

    <global-method-security pre-post-annotations="enabled"/>

    <!-- Выражения безопасности -->
    <http use-expressions="true">
        <!-- Общедоступные ресурсы -->
        <intercept-url pattern="favicon.ico" access="permitAll" />
        <intercept-url pattern="/login.xhtml" access="permitAll"/>
        <intercept-url pattern="/help/**" access="permitAll" />
        <intercept-url pattern="/resources/**" access="permitAll" />
        
        <!-- Только для пользователей системы -->
        <intercept-url pattern="/user/**" access="hasRole('user')"/>
        <intercept-url pattern="/" access="hasRole('user')"/>
        
        <!-- Только для администратора системы -->
        <intercept-url pattern="/admin/**" access="hasRole('admin')"/>
        
        <form-login login-page='/login.xhtml' default-target-url='/main.xhtml'
                    login-processing-url="/j_spring_security_check"
                    always-use-default-target='true' 
                    authentication-success-handler-ref="authenticationSuccessHandler"/>
        <http-basic/>
        <logout/>
    </http>
    
    <authentication-manager>
        <authentication-provider user-service-ref="userService">
            <password-encoder ref="passwordEncoder"/>
            <!--            <jdbc-user-service data-source-ref="dataSource"
                               users-by-username-query="
         select username, passwd as password,1 as enabled
         from people
         where username=?;"

                               authorities-by-username-query="
        select u.username, 'user' as authority
        from people u
        where u.username=?;"
            />-->
            <!--            <user-service>
                <user name="shiche" password="iS0nequo" authorities="user" />
            </user-service>-->
        </authentication-provider>
    </authentication-manager>
</beans:beans>



SecurityConfig.java
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
/**
 * Spring security.
 *
 * @author Vitaly Livshic
 */
@Configuration
public class SecurityConfig extends WebMvcConfigurationSupport
{

    /**
     * Обработчик удачного входа в систему.
     *
     * @return Обработчик.
     */
    @Bean
    public UrlAuthenticationSuccessHandler authenticationSuccessHandler()
    {
        return new UrlAuthenticationSuccessHandler();
    }

    /**
     * Шифрование паролей.
     *
     * @return Шифровщик.
     */
    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    }
}



UserServiceImpl.java

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
@Service
public class UserServiceImpl implements UserService
{

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * Сведения о пользователе по его логину. Метод требуется Spring Security.
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        List<GrantedAuthority> roles = new ArrayList<>(2);

        roles.add(new SimpleGrantedAuthority("user"));
        //roles.add(new SimpleGrantedAuthority("admin"));

        // Остальные данные
       UserDetails details = new User("shiche", passwordEncoder.encode("iS0nequo"), roles);
//        UserDetails details = new User("shiche", "iS0nequo", roles);
        if (details == null)
            throw new UsernameNotFoundException("Пользователь не найден.");
        return details;
    }



Управление исправно передается в loadUserByUsername, возвращается UserDetails со всеми разрешениями и Bad credentials.

Если убрать шифрование, аналогично. Пробовал убрать шифрование - включить '<user name="shiche" password="iS0nequo" authorities="user" />' или Jdbc авторизацию (закоменчено в security.xml). Spring выполняет запрос к БД, смотрит в памяти и исправно выдает Bad credentials.

Версия Spring Security: 4.2.3.RELEASE

Почему Spring Security выдает ошибку?
...
Рейтинг: 0 / 0
12.02.2018, 10:20
    #39600430
Щиче
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Spring Security Bad credentials
Запрос в отладчике такой:

Request URL: http://localhost:8084/tracker/j_spring_security_check
Request Method:POST
Status Code:302 Found
Remote Address:[::1]:8084
Referrer Policy:no-referrer-when-downgrade

j_username:shiche
j_password:iS0nequo
_csrf:da9213af-1609-49de-b581-d107d3f8da9f
...
Рейтинг: 0 / 0
12.02.2018, 13:03
    #39600564
Щиче
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Spring Security Bad credentials
Вопрос решен. Теперь параметры j_username и j_password в форме заменены на username, password. Сломали обратную совместимость.
...
Рейтинг: 0 / 0
Форумы / Java [игнор отключен] [закрыт для гостей] / Spring Security Bad credentials / 3 сообщений из 3, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]