Мой userRepo Null, поэтому не могу использовать FindByusername - это userdetailsserviceJAVA

Программисты JAVA общаются здесь
Anonymous
Мой userRepo Null, поэтому не могу использовать FindByusername - это userdetailsservice

Сообщение Anonymous »

Я вводил свой userRepo с @autowired.
Я могу подписать и добавить пользователей в базу данных без каких -либо проблем. Однако, когда мне приходится аутентифицировать в отношении пользователей в моей базе данных, я получаю эту проблему < /p>
, вызванный: java.lang.nullpointerexception: не может вызвать «com.workout.befit.repository.userrepo.findbyusernam com.workout.befit.services.customuserdetails.loaduserbyusername (CustomUserDetails.java:29) ~ [Classes /: Na]
at org.springframework.security.authentication.dao.daoathenticationprovider.retriveUser (daoAuthentication.1jaoathenticationprovider.retriveUser (daoAuthentication.1jaoathenticationprovider.retriveUser. ~ [Spring-Security-Core-6.4.2.jar: 6.4.2] < /p>
Это мое репо < /p>

Код: Выделить всё

package com.workout.befit.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.workout.befit.models.User;
import java.util.Optional;

public interface UserRepo extends MongoRepository {
Optional findByUsername(String username);
}

< /code>
Это моя конфигурация безопасности < /p>
package com.workout.befit.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import com.workout.befit.services.CustomUserDetails;

@Configuration
@EnableWebSecurity
@ComponentScan
public class SecurityConfig {
@Autowired
@Qualifier("customuserdetails")
CustomUserDetails customuserdetails;

@Autowired
PasswordEncoder passencoder;

@Autowired
AuthenticationProvider authprovider;

@Bean
public SecurityFilterChain securityFilterchain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize->authorize.requestMatchers("/signup","/about","/error/**").permitAll() //allow requests to signup page
.anyRequest().authenticated()) //authenticate all other requests
.httpBasic(Customizer.withDefaults())
.formLogin(Customizer.withDefaults())
.csrf(csrf->  csrf.disable());
return http.build();
}

}
< /code>
Это мой боб безопасности < /p>
package com.workout.befit.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.workout.befit.services.CustomUserDetails;

@Component
public class Securitybeans {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();}

@Bean
public UserDetailsService customuserdetailsservice(){
return new CustomUserDetails();
}

@Bean
public AuthenticationProvider authprovider(){
DaoAuthenticationProvider provider=new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder());
provider.setUserDetailsService(customuserdetailsservice());
return provider;
}
}
< /code>
Это моя пользовательская служба данных пользователя < /p>
package com.workout.befit.services;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.workout.befit.models.User;
import com.workout.befit.repository.UserRepo;

@Service("customuserdetails")
public class CustomUserDetails implements UserDetailsService {

@Autowired
UserRepo userrepo;
@Autowired
PasswordEncoder bcrypt;

@SuppressWarnings("null")
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional optionaluser=userrepo.findByUsername(username);
User user=optionaluser.orElseThrow();
UserBuilder builder = null;
builder.username(user.getUsername());
builder.password(bcrypt.encode(user.getPassword()));
builder.authorities(user.getAuthorities());
return builder.build();
}

}
Он говорит, что это. userrepo в CustomuserDetailsService - это nul>

Подробнее здесь: https://stackoverflow.com/questions/794 ... ilsservice

Вернуться в «JAVA»