我是 Spring Security 的新手,因此出于学习目的,我使用 spring-boot 2.0.3.RELEASE
和 spring-boot-starter-security
创建了一个 api。
这是我得到的
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("admin")).roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Controller 类
@RestController
@RequestMapping(value = "/security")
public class AppController {
@Autowired
SpringSecurityService service;
@GetMapping(value = "/{id}")
public Person findOne(@PathVariable("id") final int id) {
return service.findOne(id);
}
}
当我尝试通过某些浏览器使用 get 方法 findOne
时,会提示登录表单,因为所有浏览器都支持基本身份验证,我尝试使用 admin
作为用户名和密码登录但会显示来自错误凭据的错误。
我还尝试通过 postman 发送授权和 $2a$10$c6MFPW.7MD7a.2V2rJYlXO0.YOLQEmsbu5GBmFsf.jShduBPenQ6O
作为值来使用该方法。
我从这里获得了密码的值:
System.out.println(new BCryptPasswordEncoder().encode("admin"));
我知道这是一些菜鸟错误,但我不知道我错过了什么
最佳答案
在我自己的项目中尝试了您的代码。看来您只是在 WebSecurityConfigurerAdapter
上缺少 @Configuration
注释,因此正在执行默认配置。其中用户
名称和控制台中记录的密码将起作用。
关于java - 登录/使用 Api 与 Spring Security 基本身份验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60178305/