Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试使用Spring&;登录时出错;JPA?_Java_Spring_Spring Security_Spring Data Jpa - Fatal编程技术网

Java 尝试使用Spring&;登录时出错;JPA?

Java 尝试使用Spring&;登录时出错;JPA?,java,spring,spring-security,spring-data-jpa,Java,Spring,Spring Security,Spring Data Jpa,我正在尝试使用数据库中的用户登录,但出现此错误。我认为问题出现在类“UserDetailsServiceImpl”中。我必须做什么来修复此错误?如有任何提示或想法,我将不胜感激 2018-03-16 11:13:40.389 ERROR 6520 --- [nio-8080-exec-5] w.a.UsernamePasswordAuthenticationFilter : An internal error occurred while trying to authenticate the

我正在尝试使用数据库中的用户登录,但出现此错误。我认为问题出现在类“UserDetailsServiceImpl”中。我必须做什么来修复此错误?如有任何提示或想法,我将不胜感激

2018-03-16 11:13:40.389 ERROR 6520 --- [nio-8080-exec-5] 
w.a.UsernamePasswordAuthenticationFilter : An internal error occurred while trying to authenticate the user.org.springframework.security.authentication.InternalAuthenticationServiceException: failed to lazily initialize a collection of role: com.continental.qtools.fingerprints.models.User.roles, could not initialize proxy - no Session
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
这是实体“用户”

}

UserDetailsServiceImp

 @Service
 public class UserDetailsServiceImpl implements UserDetailsService {

 @Autowired
 private UserRepository userRepository;


 @Override
 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    User user = userRepository.findByUsername(username);

    System.out.println("User: " + user.getUsername());

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for (Role role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getRole()));
    }


    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
            grantedAuthorities);
}
@服务
公共类UserDetailsServiceImpl实现UserDetailsService{
@自动连线
私有用户存储库用户存储库;
@凌驾
public UserDetails loadUserByUsername(字符串用户名)引发UsernameNotFoundException{
User=userRepository.findByUsername(用户名);
System.out.println(“用户:”+User.getUsername());
Set grantedAuthories=new HashSet();
for(角色:user.getRoles()){
添加(新的SimpleGrantedAuthority(role.getRole());
}
返回新的org.springframework.security.core.userdetails.User(User.getUsername(),User.getPassword(),
授权机构);
}

}

尝试向用户对象上的roles属性添加FetchType.Anger

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", 
    joinColumns = @JoinColumn(name = "user_id"), 
    inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles;
用户类

@Entity
@Table(name = "authority")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Authority implements GrantedAuthority {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany
    @JoinTable(
            name = "authorities_privileges",
            joinColumns = @JoinColumn(
                    name = "authority_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "privilege_id", referencedColumnName = "id"))
    private Collection<Privilege> privileges;

    public Authority() {
        super();
    }

    public Authority(final String name) {
        super();
        this.name = name;
    }

    public Authority(String name,
                     Collection<Privilege> privileges) {
        this.name = name;
        this.privileges = privileges;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Collection<Privilege> getPrivileges() {
        return privileges;
    }

    public void setPrivileges(Collection<Privilege> privileges) {
        this.privileges = privileges;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (obj.toString().equals(this.name)) {
            return true;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        final Authority auth = (Authority) obj;
        if (this.name != null && this.name.equals(auth.name)) {
            return true;
        }

        return false;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]");
        return builder.toString();
    }

    @Override
    @JsonIgnore
    public String getAuthority() {
        return name;
    }
}
@Entity
@Table(name = "user_account")
public class User implements UserDetails {

    @Id
    @Column(unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "username")
    private String username;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @JsonIgnore
    @Column(name = "password", length = 60)
    private String password;

    @Column(name = "enabled")
    private boolean enabled;

    @Column(name = "last_password_reset_date")
    private Timestamp lastPasswordResetDate;

    @Column(name = "is_using_2FA")
    private boolean isUsing2FA;

    @JsonIgnore
    @Column(name = "secret", length = 60)
    private String secret;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "user_authority",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "authority_id", referencedColumnName = "id"))
    private Collection<Authority> authorities;

    public User() {
        this.secret = UUID.randomUUID().toString();
        this.enabled = false;
    }

    public User(Long id,
                String username, String firstName, String lastName,
                String email, String password,
                boolean enabled, Timestamp lastPasswordResetDate,
                boolean isUsing2FA, String secret,
                Collection<Authority> authorities) {
        this.id = id;
        this.username = username;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.enabled = enabled;
        this.lastPasswordResetDate = lastPasswordResetDate;
        this.isUsing2FA = isUsing2FA;
        this.secret = secret;
        this.authorities = authorities;
    }

    public Long getId() {
        return id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(final String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(final String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(final String username) {
        this.email = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(final String password) {
        Date date = new Date();
        this.lastPasswordResetDate = new Timestamp(date.getTime());
        this.password = password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isUsing2FA() {
        return isUsing2FA;
    }

    public void setUsing2FA(boolean isUsing2FA) {
        this.isUsing2FA = isUsing2FA;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public Timestamp getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }

    public void setLastPasswordResetDate(Timestamp lastPasswordResetDate) {
        this.lastPasswordResetDate = lastPasswordResetDate;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = (prime * result) + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final User user = (User) obj;
        if (!username.equals(user.username)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append("User [id=").append(id).append(", firstName=").append(firstName).append(", lastName=").append(lastName).append(", email=").append(email).append(", password=").append(password).append(", enabled=").append(enabled).append(", isUsing2FA=")
                .append(isUsing2FA).append(", secret=").append(secret).append(", roles=").append(authorities).append("]");
        return builder.toString();
    }
}
public class UserBuilder {
    private Long bId;
    private String bUsername;
    private String bFirstName;
    private String bLastName;
    private String bEmail;
    private String bPassword;
    private boolean bEnabled;
    private Timestamp bLastPasswordResetDate;
    private boolean bIsUsing2FA;
    private String bSecret;

    private Collection<Authority> bAuthorities;

    public UserBuilder() {
    }

    public UserBuilder(Long bId,
                       String bUsername, String bFirstName, String bLastName,
                       String bEmail, String bPassword, boolean bEnabled,
                       Timestamp bLastPasswordResetDate, boolean bIsUsing2FA, String bSecret,
                       Collection<Authority> authorities) {
        this.bId = bId;
        this.bUsername = bUsername;
        this.bFirstName = bFirstName;
        this.bLastName = bLastName;
        this.bEmail = bEmail;
        this.bPassword = bPassword;
        this.bEnabled = bEnabled;
        this.bLastPasswordResetDate = bLastPasswordResetDate;
        this.bIsUsing2FA = bIsUsing2FA;
        this.bSecret = bSecret;
        this.bAuthorities = bAuthorities;
    }

    public UserBuilder(User user) {
        this.bId = user.getId();
        this.bUsername = user.getUsername();
        this.bFirstName = user.getFirstName();
        this.bLastName = user.getLastName();
        this.bEmail = user.getEmail();
        this.bPassword = user.getPassword();
        this.bEnabled = user.isEnabled();
        this.bLastPasswordResetDate = user.getLastPasswordResetDate();
        this.bIsUsing2FA = user.isUsing2FA();
        this.bSecret = user.getSecret();
    }

    public User createUser() {
        return new User(bId,
                bUsername,
                bFirstName,
                bLastName,
                bEmail,
                bPassword,
                bEnabled,
                bLastPasswordResetDate,
                bIsUsing2FA,
                bSecret,
                bAuthorities
        );
    }


    public UserBuilder bId(Long bId) {
        this.bId = bId;
        return this;
    }

    public UserBuilder bUsername(String bUsername) {
        this.bUsername = bUsername;
        return this;
    }

    public UserBuilder bFirstName(String bFirstName) {
        this.bFirstName = bFirstName;
        return this;
    }

    public UserBuilder bLastName(String bLastName) {
        this.bLastName = bLastName;
        return this;
    }

    public UserBuilder bEmail(String bEmail) {
        this.bEmail = bEmail;
        return this;
    }

    public UserBuilder bPassword(String bPassword) {
        Date date = new Date();
        this.bLastPasswordResetDate = new Timestamp(date.getTime());
        this.bPassword = bPassword;
        return this;
    }

    public UserBuilder bEnabled(boolean bEnabled) {
        this.bEnabled = bEnabled;
        return this;
    }

    public UserBuilder bLastPasswordResetDate(Timestamp bLastPasswordResetDate) {
        this.bLastPasswordResetDate = bLastPasswordResetDate;
        return this;
    }

    public UserBuilder bIsUsing2FA(boolean bIsUsing2FA) {
        this.bIsUsing2FA = bIsUsing2FA;
        return this;
    }

    public UserBuilder bSecret(String bSecret) {
        this.bSecret = bSecret;
        return this;
    }

    public UserBuilder bAuthorities(Collection<Authority> bAuthorities) {
        this.bAuthorities = bAuthorities;
        return this;
    }
}
@Service("userDetailsService")
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @SuppressWarnings("unchecked")
    @Override
    public UserDetails loadUserByUsername(final String identity) throws UsernameNotFoundException {
        try {
            final User user = Optional.ofNullable(userRepository.findByEmail(identity)).orElseGet(() -> userRepository.findByUsername(identity));

            if (user == null) {
                throw new UsernameNotFoundException("No user found with username: " + identity);
            }

            //Collection<Authority> authorities = getAuthorities((Collection<Authority>) user.getAuthorities());
            Collection<Authority> authorities = getAuthorities((Collection<Authority>) user.getAuthorities());

            return new UserBuilder(user).bAuthorities(authorities).createUser();

        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    private final Collection<Authority> getAuthorities(final Collection<Authority> authorityList) {
        return getGrantedAuthorities(getAuthorityList(authorityList));
    }

    private final List<String> getAuthorityList(final Collection<Authority> authorityList) {
        final List<String> authorities = new ArrayList<String>();

        for (final Authority authority : authorityList) {
            authorities.add(authority.getName());

            if (authority.getPrivileges() == null || authority.getPrivileges().isEmpty()) continue;

            // Add all Privileges as Authorities
            for (final Privilege item : authority.getPrivileges()) {
                authorities.add(item.getName());
            }
        }

        return authorities;
    }

    private final Collection<Authority> getGrantedAuthorities(final List<String> authorityList) {
        final List<Authority> grantedAuthorities = new ArrayList<Authority>();
        for (final String authority : authorityList) {
            grantedAuthorities.add(new Authority(authority));
        }
        return grantedAuthorities;
    }
}
public interface PrivilegeRepository extends JpaRepository<Privilege, Long> {

    Privilege findByName(String name);

    @Override
    void delete(Privilege privilege);

}

public interface RoleRepository extends JpaRepository<Authority, Long> {

    Authority findByName(String name);

    @Override
    void delete(Authority role);

}

public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);

    User findByUsername(String username);

    @Override
    void delete(User user);
}
@实体
@表(name=“用户账户”)
公共类用户实现UserDetails{
@身份证
@列(unique=true,nullable=false)
@GeneratedValue(策略=GenerationType.AUTO)
私人长id;
@列(name=“username”)
私有字符串用户名;
@列(name=“first_name”)
私有字符串名;
@列(name=“last_name”)
私有字符串lastName;
@列(name=“email”)
私人字符串电子邮件;
@杰索尼奥雷
@列(name=“password”,长度=60)
私有字符串密码;
@列(name=“enabled”)
启用私有布尔值;
@列(name=“上次密码重置日期”)
私有时间戳lastPasswordResetDate;
@列(name=“is_using_2FA”)
私有布尔值使用2fa;
@杰索尼奥雷
@列(name=“secret”,长度=60)
私人字符串秘密;
@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(name=“user\u authority”,
joinColumns=@JoinColumn(name=“user\u id”,referencedColumnName=“id”),
inverseJoinColumns=@JoinColumn(name=“authority\u id”,referencedColumnName=“id”))
私人收藏机构;
公共用户(){
this.secret=UUID.randomUUID().toString();
this.enabled=false;
}
公共用户(长id,
字符串用户名、字符串名、字符串名、,
字符串电子邮件,字符串密码,
启用布尔值,时间戳lastPasswordResetDate,
布尔值使用2fa,字符串secret,
(收集当局){
this.id=id;
this.username=用户名;
this.firstName=firstName;
this.lastName=lastName;
this.email=电子邮件;
this.password=密码;
this.enabled=已启用;
this.lastPasswordResetDate=lastPasswordResetDate;
this.isUsing2FA=isUsing2FA;
这个秘密;
这个.权威=权威;
}
公共长getId(){
返回id;
}
公共无效集合id(最终长id){
this.id=id;
}
公共字符串getFirstName(){
返回名字;
}
public void setFirstName(最终字符串firstName){
this.firstName=firstName;
}
公共字符串getLastName(){
返回姓氏;
}
public void setLastName(最终字符串lastName){
this.lastName=lastName;
}
公共字符串getEmail(){
回复邮件;
}
public void setEmail(最终字符串用户名){
this.email=用户名;
}
公共字符串getPassword(){
返回密码;
}
public void setPassword(最终字符串密码){
日期=新日期();
this.lastPasswordResetDate=新的时间戳(date.getTime());
this.password=密码;
}
@凌驾
公共字符串getUsername(){
返回用户名;
}
public void setUsername(字符串用户名){
this.username=用户名;
}
公共布尔值正在使用2fa(){
返回使用2FA;
}
使用2fa的公共无效设置(布尔值使用2fa){
this.isUsing2FA=isUsing2FA;
}
公共字符串getSecret(){
归还秘密;
}
公共无效设置机密(字符串机密){
这个秘密;
}
@凌驾

public Collection尝试将
@Transactional
添加到方法
loadUserByUsername

请提供一个简短的示例,而不是完整的代码,以及确切的问题出在哪里。是否遵循stacktrace?…无法初始化代理…不,如何遵循stacktrace?我想指出,在如果使用oString方法,则应该从toString方法中删除角色和项目。默认情况下,许多关系的FetchType是惰性的,但这是因为toString()的缘故方法它急切地获取数据。您使用的是哪个数据库?如果您使用的是oracle,请检查数据库版本和客户端版本。当您使用10g作为客户端,11g作为数据库时,密码和用户名会发送到upper-caseorg.springframework.security.authentication.InternalAuthenticationServiceException中的数据库:无法提取t ResultSet;SQL[n/a];嵌套异常为org.hibernate.exception.sqlgrammareexception:无法提取org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126)~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]在org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144)Shoot.Ok.Yeah,确保loadUserByUsername方法或UserDetailsServiceImpl类上有@Transnational。就我个人而言,我喜欢让我的用户类imp
public class UserBuilder {
    private Long bId;
    private String bUsername;
    private String bFirstName;
    private String bLastName;
    private String bEmail;
    private String bPassword;
    private boolean bEnabled;
    private Timestamp bLastPasswordResetDate;
    private boolean bIsUsing2FA;
    private String bSecret;

    private Collection<Authority> bAuthorities;

    public UserBuilder() {
    }

    public UserBuilder(Long bId,
                       String bUsername, String bFirstName, String bLastName,
                       String bEmail, String bPassword, boolean bEnabled,
                       Timestamp bLastPasswordResetDate, boolean bIsUsing2FA, String bSecret,
                       Collection<Authority> authorities) {
        this.bId = bId;
        this.bUsername = bUsername;
        this.bFirstName = bFirstName;
        this.bLastName = bLastName;
        this.bEmail = bEmail;
        this.bPassword = bPassword;
        this.bEnabled = bEnabled;
        this.bLastPasswordResetDate = bLastPasswordResetDate;
        this.bIsUsing2FA = bIsUsing2FA;
        this.bSecret = bSecret;
        this.bAuthorities = bAuthorities;
    }

    public UserBuilder(User user) {
        this.bId = user.getId();
        this.bUsername = user.getUsername();
        this.bFirstName = user.getFirstName();
        this.bLastName = user.getLastName();
        this.bEmail = user.getEmail();
        this.bPassword = user.getPassword();
        this.bEnabled = user.isEnabled();
        this.bLastPasswordResetDate = user.getLastPasswordResetDate();
        this.bIsUsing2FA = user.isUsing2FA();
        this.bSecret = user.getSecret();
    }

    public User createUser() {
        return new User(bId,
                bUsername,
                bFirstName,
                bLastName,
                bEmail,
                bPassword,
                bEnabled,
                bLastPasswordResetDate,
                bIsUsing2FA,
                bSecret,
                bAuthorities
        );
    }


    public UserBuilder bId(Long bId) {
        this.bId = bId;
        return this;
    }

    public UserBuilder bUsername(String bUsername) {
        this.bUsername = bUsername;
        return this;
    }

    public UserBuilder bFirstName(String bFirstName) {
        this.bFirstName = bFirstName;
        return this;
    }

    public UserBuilder bLastName(String bLastName) {
        this.bLastName = bLastName;
        return this;
    }

    public UserBuilder bEmail(String bEmail) {
        this.bEmail = bEmail;
        return this;
    }

    public UserBuilder bPassword(String bPassword) {
        Date date = new Date();
        this.bLastPasswordResetDate = new Timestamp(date.getTime());
        this.bPassword = bPassword;
        return this;
    }

    public UserBuilder bEnabled(boolean bEnabled) {
        this.bEnabled = bEnabled;
        return this;
    }

    public UserBuilder bLastPasswordResetDate(Timestamp bLastPasswordResetDate) {
        this.bLastPasswordResetDate = bLastPasswordResetDate;
        return this;
    }

    public UserBuilder bIsUsing2FA(boolean bIsUsing2FA) {
        this.bIsUsing2FA = bIsUsing2FA;
        return this;
    }

    public UserBuilder bSecret(String bSecret) {
        this.bSecret = bSecret;
        return this;
    }

    public UserBuilder bAuthorities(Collection<Authority> bAuthorities) {
        this.bAuthorities = bAuthorities;
        return this;
    }
}
@Service("userDetailsService")
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @SuppressWarnings("unchecked")
    @Override
    public UserDetails loadUserByUsername(final String identity) throws UsernameNotFoundException {
        try {
            final User user = Optional.ofNullable(userRepository.findByEmail(identity)).orElseGet(() -> userRepository.findByUsername(identity));

            if (user == null) {
                throw new UsernameNotFoundException("No user found with username: " + identity);
            }

            //Collection<Authority> authorities = getAuthorities((Collection<Authority>) user.getAuthorities());
            Collection<Authority> authorities = getAuthorities((Collection<Authority>) user.getAuthorities());

            return new UserBuilder(user).bAuthorities(authorities).createUser();

        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    private final Collection<Authority> getAuthorities(final Collection<Authority> authorityList) {
        return getGrantedAuthorities(getAuthorityList(authorityList));
    }

    private final List<String> getAuthorityList(final Collection<Authority> authorityList) {
        final List<String> authorities = new ArrayList<String>();

        for (final Authority authority : authorityList) {
            authorities.add(authority.getName());

            if (authority.getPrivileges() == null || authority.getPrivileges().isEmpty()) continue;

            // Add all Privileges as Authorities
            for (final Privilege item : authority.getPrivileges()) {
                authorities.add(item.getName());
            }
        }

        return authorities;
    }

    private final Collection<Authority> getGrantedAuthorities(final List<String> authorityList) {
        final List<Authority> grantedAuthorities = new ArrayList<Authority>();
        for (final String authority : authorityList) {
            grantedAuthorities.add(new Authority(authority));
        }
        return grantedAuthorities;
    }
}
public interface PrivilegeRepository extends JpaRepository<Privilege, Long> {

    Privilege findByName(String name);

    @Override
    void delete(Privilege privilege);

}

public interface RoleRepository extends JpaRepository<Authority, Long> {

    Authority findByName(String name);

    @Override
    void delete(Authority role);

}

public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);

    User findByUsername(String username);

    @Override
    void delete(User user);
}
@Component
public class SetupDataLoader implements ApplicationListener<ContextRefreshedEvent> {

    private boolean alreadySetup = false;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PrivilegeRepository privilegeRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    BeerRepository beerRepository;

    @Override
    @Transactional
    public void onApplicationEvent(final ContextRefreshedEvent event) {
        if (alreadySetup) {
            return;
        }

        // == create initial privileges
        final Privilege userReadPrivilege = createPrivilegeIfNotFound("USER_READ_PRIVILEGE");
        final Privilege userWritePrivilege = createPrivilegeIfNotFound("USER_WRITE_PRIVILEGE");
        final Privilege beerReadPrivilege = createPrivilegeIfNotFound("BEER_READ_PRIVILEGE");
        final Privilege beerWritePrivilege = createPrivilegeIfNotFound("BEER_WRITE_PRIVILEGE");
        final Privilege passwordPrivilege = createPrivilegeIfNotFound("CHANGE_PASSWORD_PRIVILEGE");

        // == create initial roles
        final List<Privilege> adminPrivileges = new ArrayList<Privilege>(Arrays.asList(beerReadPrivilege, beerWritePrivilege, userReadPrivilege, userWritePrivilege, passwordPrivilege));
        final List<Privilege> userPrivileges = new ArrayList<Privilege>(Arrays.asList(beerReadPrivilege, beerWritePrivilege));
        final Authority adminAuthority = createRoleIfNotFound("ROLE_ADMIN", adminPrivileges);
        createRoleIfNotFound("ROLE_USER", userPrivileges);

        // == create initial user
        createUserIfNotFound("rdurden",
                "rdurden@example.com",
                "Rupert",
                "Durden",
                "ILikeBeer2!",
                new ArrayList<Authority>(Arrays.asList(adminAuthority)));

        alreadySetup = true;
    }

    @Transactional
    Privilege createPrivilegeIfNotFound(final String name) {
        Privilege privilege = privilegeRepository.findByName(name);
        if (privilege == null) {
            privilege = new Privilege(name);
            privilege = privilegeRepository.save(privilege);
        }
        return privilege;
    }

    @Transactional
    Authority createRoleIfNotFound(final String name, final Collection<Privilege> privileges) {
        Authority authority = roleRepository.findByName(name);
        if (authority == null) {
            authority = new Authority(name);
        }
        authority.setPrivileges(privileges);
        authority = roleRepository.save(authority);
        return authority;
    }

    @Transactional
    User createUserIfNotFound(final String username, final String email, final String firstName, final String lastName, final String password, final Collection<Authority> authorities) {
        User user = Optional.ofNullable(userRepository.findByEmail(email)).orElseGet(() -> userRepository.findByUsername(username));

        if (user != null) return user;

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        Date lastMonthDate = cal.getTime();
        Timestamp lastMonthTimestamp = new Timestamp(lastMonthDate.getTime());

        user = new UserBuilder()
                .bAuthorities(authorities)
                .bUsername(username)
                .bFirstName(firstName)
                .bLastName(lastName)
                .bEmail(email)
                .bPassword(passwordEncoder.encode(password))
                .bIsUsing2FA(false)
                .bEnabled(true)
                .bLastPasswordResetDate(lastMonthTimestamp)
                .createUser();

        user = userRepository.save(user);
        return user;
    }
}