“401:凭据错误”在Spring Boot中通过url进行基本身份验证

时间:2016-03-01 09:59:04

标签: spring authentication spring-security basic-authentication

我正在尝试使用Spring安全性进行基本身份验证。我也希望通过url(用户名:password@mysite.com)来实现。当我执行这样的http请求时,授权标头设置正确,这也是我的SecurityConfig:

 12 @Configuration
 13 @EnableGlobalMethodSecurity(prePostEnabled = true)
 14 @EnableWebSecurity
 15 public class SecurityConfig extends WebSecurityConfigurerAdapter {
 16 
 17   @Override
 18   protected void configure(HttpSecurity http) throws Exception {
 19     http.authorizeRequests()
 20       .antMatchers("/login").permitAll()
 21       .antMatchers("/admin/**").hasRole("ADMIN")
 22       .anyRequest().authenticated();
 23     http.httpBasic();
 24     http.csrf().disable();
 25   }
 26 
 27   @Autowired
 28   public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
 29     auth.inMemoryAuthentication()
 30         .withUser("user").password("pwd1").roles("USER").and()
 31         .withUser("admin").password("pwd2").roles("ADMIN", "USER");
 32   }
 33 
 34 }

这是我的AdminController:

 24 @PreAuthorize("hasRole('ADMIN')")
 25 @RequestMapping(value="/admin")
 26 @Controller
 27 public class AdminController {
154   @RequestMapping(value="/", method=RequestMethod.GET)
155   public  String admin(Model model) {
156     return Constants.ADMIN_TEMPLATE;
157   }
177 }

当我尝试提出如下请求时:

admin:pwd2@localhost:3000/admin

我得到“401:Bad Credentials”。为什么会这样? (我也尝试使用具有相同结果的restclient通过Authorization标头发出请求)

感谢。

1 个答案:

答案 0 :(得分:0)

删除http.httpBasic();然后再试一次