【发布时间】:2019-10-24 21:15:20
【问题描述】:
我对 Spring Boot 和 Spring Security 还很陌生。通过各种教程和讲座,我实现了一个小型 Spring Boot 应用程序,现在我正在尝试保护我的端点。
我创建了一个扩展 WebSecurityConfigurerAdapter 的安全配置,我用它来保护我的应用程序。
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
public void configureGlobal(AuthenticationManagerBuilder authManager) throws Exception
{
authManager
.inMemoryAuthentication()
.withUser("carAdmin").password(passwordEncoder().encode("carAdmin123")).roles("CAR_ADMIN")
.and()
.withUser("driverAdmin").password(passwordEncoder().encode("driverAdmin123")).roles("DRIVER_ADMIN", "DRIVER")
.and()
.withUser("driver").password("driver@123").roles("DRIVER");
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable().formLogin().disable()
.headers().frameOptions().disable().and()
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/cars/**").hasAnyRole("CAR_ADMIN")
.antMatchers("/drivers/**").hasAnyRole("DRIVER_ADMIN", "DRIVER")
.anyRequest().authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
在我的 RestAPI 资源中,我使用了@PreAuthorize。
@GetMapping("/{carId}")
@PreAuthorize("hasRole('ROLE_CAR_ADMIN')")
public CarDTO getCar(@Valid @PathVariable long carId) throws EntityNotFoundException {
return CarMapper.makeCarDTO(carService.find(carId));
}
我想用 Postman 测试一下。
另外,我还在网上看到我们可以创建网页来实现身份验证,但我正在寻找非常基本的身份验证。这样,我可以使用基本身份验证和 Postman 对其进行测试。
目前使用这种方法,我在 Postman 中选择 basic auth,传递用户名和密码但得到 Forbidden, access denied.
我不知道我做错了什么或如何解决它。
任何帮助将不胜感激。
【问题讨论】:
标签: spring spring-boot spring-security