我是Java和Spring的新手。
每次我发送一个post请求到我的服务器与一个用户的详细信息,已经存在于我的数据库中,我总是得到一个401未经授权的响应,我不知道为什么。
安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Autowired
AuthUserService authUserService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().disable();
http.httpBasic().authenticationEntryPoint(new BasicAuthenticationEntryPoint());
http.authorizeHttpRequests()
.requestMatchers(HttpMethod.POST, "/api/v1/login").authenticated()
.and()
.authorizeHttpRequests().anyRequest().permitAll();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
}
protected void configure (AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(authUserService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
如果你使用数据库的用户凭据登录,那么你必须使用DaoAuthenticationProvider
,然后只有Spring Security知道它必须匹配你输入的凭据与数据库凭据登录。
然后你必须使用UserDetailsService
接口从数据库加载用户,然后Spring Security将匹配凭据并授予访问权限。
在你的SecurityConfiguration
类中提到下面的代码。
@Resource
private UserDetailsService userDetailsService;
@Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
那么你必须创建UserDetailServiceImpl
类来实现UserDetailService
接口。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
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;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Users user1 = userRepository.findByEmail(username);
if (user1 == null) {
throw new UsernameNotFoundException(username);
}
UserDetails user = User
.withUsername(user1.getName())
.password(user1.getPassword())
.build();
return user;
}
}
如果你在你的项目中使用Spring Data JPA,并且你已经用UserRepository
扩展了JpaRepository
或CrudRepository
,并且你在UserRepository
中有findByEmail
方法,这将起作用。
如果您想了解更多关于如何使用Spring Data JPA以及如何使用数据库值执行登录的信息,请在此注释