每个请求的 Spring Boot Basic Auth,为以后的请求验证用户名
Posted
技术标签:
【中文标题】每个请求的 Spring Boot Basic Auth,为以后的请求验证用户名【英文标题】:Spring Boot Basic Auth for each request, username validated for later requests 【发布时间】:2017-11-16 14:17:43 【问题描述】:我在 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 需要针对每个请求进行验证。
我在这里做错了什么吗?
【问题讨论】:
能贴出 DaoAuthenticationProvider 的代码吗? 【参考方案1】:将无状态添加到配置有助于解决问题。
@Override
protected void configure(HttpSecurity http) throws Exception
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().httpBasic();
【讨论】:
以上是关于每个请求的 Spring Boot Basic Auth,为以后的请求验证用户名的主要内容,如果未能解决你的问题,请参考以下文章
Spring boot security rest basic Authentication example
Spring Boot - Filter实现简单的Http Basic认证
为啥 Spring boot Security Basic Authentication 慢?