Я использую Spring и Hibernate. В моей базе данных у меня есть несколько пользователей с 3 разными ролями. Я использую BCryptPasswordEncoder, в базе данных у меня есть пользователи с простым паролем, закодированным паролем и паролем в кодировке {bcrypt}, у меня проблема, потому что когда я набираю пользователей с простыми паролями, я могу войти в систему, когда я набираю закодированный пароль или { bcrypt}, я не могу войти в систему.
SecurityConfig.java
package com.spring.config;
import com.spring.service.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth ) throws Exception {
auth.authenticationProvider(authProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/managers/**").hasRole("MANAGER")
.antMatchers("/employees/**").hasRole("REGULAR_EMPLOYEE")
.antMatchers("/").permitAll()
.and().formLogin().loginPage("/").defaultSuccessUrl("/login").loginProcessingUrl("/loginAction").permitAll()
.and().logout().permitAll();
}
@Bean
public UserDetailsService userDetailsService(){
return new UserDetails();
}
@Autowired
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(bCryptPasswordEncoder());
return authProvider;
}
}
UserDetails.java
package com.spring.service;
import com.spring.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class UserDetails implements UserDetailsService {
@Autowired
private UserService mUserService;
@Override
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = mUserService.getUserByLogin(s);
org.springframework.security.core.userdetails.User.UserBuilder userBuilder;
userBuilder = org.springframework.security.core.userdetails.User.withUsername(user.getAccountLogin());
userBuilder.password(new BCryptPasswordEncoder().encode(user.getAccountPassword()));
userBuilder.roles(user.getRoleByRoleId().getRole());
return userBuilder.build();
}
}
простой-логин.jsp
<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType = "text/html;charset=UTF-8" language = "java" %>
<html>
<head>
<title>Log in</title>
<meta charset = "UTF-8">
<style>
.failed {
color: red;
}
.success {
color: green;
}
</style>
</head>
<body>
<form:form action = "${pageContext.request.contextPath}/loginAction"
method = "POST">
<c:if test = "${param.error != null}">
<i class = "failed">Wrong data!</i>
</c:if>
<c:if test = "${param.logout != null}">
<i class = "success">Logged out successfully!</i>
</c:if>
<p>
Login: <input type = "text" name = "username" />
</p>
<p>
Password: <input type = "password" name = "password" />
</p>
<input type = "submit" value = "Log in" />
</form:form>
</body>
</html>
Весенняя версия 5.0.3, это просто весна
Йогеш Бадке, у меня был @Bean в другом классе, я изменил его, но это не помогает: /
Конечно, это не сработает ... Вы всегда кодируете пароль с помощью BCRypt ... Вы шифруете закодированный пароль с помощью bcrypt и кодируете зашифрованный пароль с помощью bcrypt ... В основном ваш UserDetails (служебная вещь) ломает все, кроме простые пароли.
Да ты прав :), глупая ошибка, спасибо за помощь :)!




Разве метод
bCryptPasswordEncoder()не следует аннотировать с помощью@Beanвместо@Autowired, поскольку вы объявляете, что компонент не внедряет его?