使用Postman测试GET接口遇401 Unauthorized问题求助
问题描述
- 测试接口:
GET http://localhost:8080/hotels(查询所有酒店) - 无授权(no auth)请求返回401错误:
{ "timestamp": "2022-08-17T04:43:07.249+00:00", "status": 401, "error": "Unauthorized", "path": "/hotels" }
- 切换为Basic Auth授权时,Postman提示
could not get a response - 后端Spring Security配置:
protected void configure(HttpSecurity security) throws Exception { security .csrf().disable() .cors().disable() .authorizeRequests() .antMatchers("/trip", "/hotels") .hasAnyAuthority("ADMIN") .and() .httpBasic() .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); }
解决方案
1. 401错误的原因(无授权请求)
根据配置,/hotels接口要求访问者拥有ADMIN权限,且启用了HTTP Basic认证。无授权请求未携带任何身份凭证,因此返回401是符合预期的安全拦截结果。
2. Basic Auth无响应的排查步骤
(1)验证Postman配置正确性
- 确认Basic Auth标签页中输入的用户名/密码对应系统中拥有
ADMIN权限的用户 - 手动构造Authorization请求头测试:将
用户名:密码进行Base64编码后,添加请求头Authorization: Basic [编码后的字符串],再发送请求
(2)检查后端认证逻辑配置
Spring Security的HTTP Basic认证需要配套的用户信息查询和密码校验逻辑,需确认:
- 已实现
UserDetailsService接口,能够从数据库或其他数据源中查询到对应用户,且用户的权限集合包含ADMIN - 已配置
PasswordEncoder(如BCryptPasswordEncoder),且数据库中存储的用户密码是经过该编码器加密后的结果 - 确保上述两个Bean已正确注册到Spring容器中,示例配置:
@Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public UserDetailsService userDetailsService(UserRepository userRepository) { return username -> { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found"); } return User.withUsername(user.getUsername()) .password(user.getPassword()) .authorities(user.getAuthorities()) .build(); }; }
(3)服务可用性检查
- 确认后端服务正常运行在
localhost:8080端口,无端口冲突或服务崩溃情况 - 检查本地防火墙、代理工具是否拦截了Postman的请求
- 尝试用curl命令测试,排除Postman客户端问题:
curl -u username:password http://localhost:8080/hotels
3. 额外验证点
- 确认数据库中目标用户的权限字段正确设置为
ADMIN(注意权限字符串大小写,配置中是ADMIN,需和数据库存储一致) - 若使用其他认证方式,需检查是否存在冲突的认证过滤器配置
内容的提问来源于stack exchange,提问作者Bastian_Wind
相关产品推荐
相关产品推荐

