gpt4 book ai didi

spring-boot - 每个请求的 Spring Boot Basic Auth,为以后的请求验证用户名

转载 作者:行者123 更新时间:2023-12-03 23:18:15 26 4
gpt4 key购买 nike

我在 Spring Boot 中启用了 http 基本身份验证。从 Postman 打电话时,我看到奇怪的结果

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private ApiUserDetailsService userDetails;

@Bean
public ShaPasswordEncoder passwordEncoder() {
return new ShaPasswordEncoder();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
ReflectionSaltSource salt = new ReflectionSaltSource();
salt.setUserPropertyToUse("username");
DaoAuthenticationProvider dao = new DaoAuthenticationProvider();
dao.setUserDetailsService(userDetails);
dao.setPasswordEncoder(passwordEncoder());
dao.setSaltSource(salt);
auth.authenticationProvider(dao);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().httpBasic();
}

客户详细信息
@Service
public class ApiUserDetailsService implements UserDetailsService {

@Autowired
private JdbcTemplate jdbcTemplate;

@Value("${spring.queries.users.query}")
private String usersQuery;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<UserDetails> usersBasedOnUserName = getUsersBasedOnUserName(username);

if (usersBasedOnUserName.size() == 0) {
throw new UsernameNotFoundException("Username " + username + " not found");
}
return usersBasedOnUserName.get(0);
}

private List<UserDetails> getUsersBasedOnUserName(String username) {
return jdbcTemplate.query(this.usersQuery, new String[] {username}, new RowMapper<UserDetails>() {
@Override
public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
return new User(username, password, AuthorityUtils.NO_AUTHORITIES);
}
});
}

}

我第一次执行请求时,它需要正确的凭据。在我输入正确的凭据后,我得到了结果。但是当我尝试在没有凭据或不同密码保持用户名相同的情况下执行相同的请求时,我不会收到 401 错误。

只有当我更改用户名时才会出现 401 错误。

我的 API 需要针对每个请求进行验证。

我在这里做错了什么。

最佳答案

将无状态添加到配置有助于解决问题。

@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().httpBasic();
}

关于spring-boot - 每个请求的 Spring Boot Basic Auth,为以后的请求验证用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com