#java #spring-boot #spring-mvc #authentication #spring-security
Вопрос:
spring security не использует данные из базы данных для аутентификации и генерации пароля в консоли, а также не использует мою настроенную форму входа.
Основной класс—
package mis.main; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @ComponentScan({"mis.controller", "mis.services"}) @EntityScan("mis.entity") @EnableJpaRepositories("mis.dao") public class BitmisApplication { public static void main(String[] args) { SpringApplication.run(BitmisApplication.class, args); } }
Пользовательские данные—
package mis.config; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import mis.entity.Roles; import mis.entity.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; public class CustomUserDetails implements UserDetails { private User user; public CustomUserDetails(User user) { this.user = user; } @Override public Collectionlt;? extends GrantedAuthoritygt; getAuthorities() { Setlt;Rolesgt; roles = user.getRoles(); Listlt;SimpleGrantedAuthoritygt; authorities = new ArrayListlt;gt;(); for (Roles role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getUsername(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return user.isEnabled(); } }
Класс MyConfig—
package mis.config; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 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 @EnableAutoConfiguration @EnableWebSecurity public class MyConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService userDetailsService() { return new UserDetailsServiceImpl(); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService()); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").hasAnyAuthority("USER", "CREATOR", "EDITOR", "ADMIN") .antMatchers("/new").hasAnyAuthority("ADMIN", "CREATOR") .antMatchers("/admin/**").hasAnyAuthority("ADMIN", "EDITOR") .antMatchers("/delete/**").hasAuthority("ADMIN") .anyRequest().authenticated() .and() .formLogin().permitAll() .and() .logout().permitAll() .and() .exceptionHandling().accessDeniedPage("/403") ; } }
UserDetailsServiceImpl—
package mis.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import mis.entity.User; import mis.dao.UserRepository; public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.getUserByUsername(username); if (user == null) { throw new UsernameNotFoundException("Could not find user"); } return new CustomUserDetails(user); } }
Информация для пользователей—
«посылка ошибочна».;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import mis.entity.User; public interface UserRepository extends JpaRepositorylt;User, Longgt; { @Query("SELECT u FROM User u WHERE u.username = :username") public User getUserByUsername(@Param("username") String username); }"
Я думаю, что springboot не может прочитать эти файлы аутентификации
Комментарии:
1. Вы пробовали установить
@ComponentScan({"mis"})
?2. Из-за вашей структуры упаковки вещи не забираются. Вместо того, чтобы помещать свой
BitmisApplication
вmis.main
, переместите его тудаmis
. Выбросьте все аннотации, но@SpringBootApplication
и все будет работать.3. Да, я пытался, но не получилось
4. пожалуйста, не просто публикуйте свой код и не объясняйте в одном предложении, что он не работает. Где ваши журналы, шаги для воспроизведения, ваши запросы, отсутствие деталей отладки, отклоненные и проголосованные за закрытие.
Ответ №1:
приложение spring не может найти ваши конфигурации, так как структура вашего проекта повреждена, и вы добавили неправильную пользовательскую конфигурацию.
@SpringBootApplication
класс по умолчанию будет сканировать пакет, в котором он находится, mis.main
и все пакеты ниже этого (mis.main…* и т. Д.), Чтобы найти все аннотированные классы spring и загрузить их.
Вы разместили свои файлы конфигурации mis.config
, которые не находятся непосредственно ниже mis.main
, и у вас есть файлы, mis.entity
которые также не находятся ниже mis.main
.
Вы также добавили
@ComponentScan({"mis.controller", "mis.services"}) @EntityScan("mis.entity")
для того, чтобы попытаться найти файлы конфигурации, но не удалось указать mis.config
в качестве папки для сканирования.
Самым простым решением было бы
- удалите две аннотации, о которых я упоминал выше.
- переместите основной класс в пакет
mis
, а затем удалите пакетmis.main
, чтобы основной класс находился в корне проекта.
некоторые другие вещи:
@Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService()); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); }
не требуется и может быть удален, потому что вы объявили обычай UserDetailsService
, и PasswordEncoder
в качестве компонентов они будут автоматически подхвачены системой и включены в spring, и она автоматически настроит для вас DaoAuthentication.
Если вы учитесь, вам следует прочитать справочные документы по безопасности spring, все это упоминается там.
Комментарии:
1. Спасибо, это сработало для меня