Я новенький в java и Spring недавно начал его изучать. решил сделать аутентификацию на своём тестовом сайте с помощью UserDetailsService. Но она не работает. Постоянно пишет, что такого пользователя нет в базе данных mysql. В модели User и Enum'е roles я
Код UserService:
package com.IDS.LinkStack.services;
import com.IDS.LinkStack.domain.User;
import com.IDS.LinkStack.repos.UserRepository;
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 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Collections;
import static com.IDS.LinkStack.domain.Role.USER;
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findByUsername(username);
}
public Boolean saveUser(User user){
user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
if(userRepository.findByUsername(user.getUsername()) != null)
return false;
user.setRoles(Collections.singleton(USER));
userRepository.save(user);
return true;
}
}
WebSecurityConfig:
package com.IDS.LinkStack.configs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import com.IDS.LinkStack.services.UserService;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/images/**", "/signup", "/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
}
}
User Model
package com.IDS.LinkStack.domain;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
@Entity
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String username;
@NotNull
private String password;
@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_role", joinColumns =@JoinColumn(name="user_id"))
@Enumerated(EnumType.STRING)
private Set<Role> roles;
@OneToMany(fetch = FetchType.EAGER)
private List<Link> links = new ArrayList<Link>();
private User(){}
public User(String username, String password){
this.username = username;
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return false;
}
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() { return password; }
public Set<Role> getRoles() {
return roles;
}
public List<Link> getLinks() {
return links;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setLinks(List<Link> links) {
this.links = links;
}
}
Role enum
package com.IDS.LinkStack.domain;
import org.springframework.security.core.GrantedAuthority;
public enum Role implements GrantedAuthority {
USER;
@Override
public String getAuthority() {
return name();
}
}