我查阅了有关使用Spring Security的文章,但它们并没有完全满足我的需求。它们通常处理内存用户和明文密码。
我想要实现的目标:
客户端使用基本身份验证进行身份验
安全控制器方法如下所示:
@RequestMapping(value = "/test")
public ResponseEntity test(@AuthenticationPrincipal MyUser user){
// Logic
}
如果给定用户经过身份验证,我希望控制器方法在其参数中获取MyUser对象,否则返回null。
我在数据库中存储散列密码和用户的salt,我有一个服务,它验证给定的用户名 - 密码对并返回一个User对象,如果验证成功或失败,则返回null。
现在需要做的就是拦截每个请求,查看基本身份验证标头,将信息传递给我的自定义身份验证服务,然后将其结果传递给控制器方法。不幸的是我无法做到这一点。
我读到使用自定义UserDetailsService
,但这似乎只能处理从数据库中获取用户数据,而不是任何身份验证。我无法弄清楚如何将所有组件连接在一起。
你能指出我正确的方向如何让这个相当简单的工作流程工作吗?
编辑
我没有使用XML配置,我唯一的安全相关配置是:
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").csrf().disable();
http.authorizeRequests()
.antMatchers("/user").permitAll()
.antMatchers("/user/**").permitAll()
.anyRequest().authenticated();
}
}
我认为这篇文章会有所帮助,因为据我所知这是你想要做的http://www.baeldung.com/spring-security-authentication-provider
您可以通过3种不同方式进行基本身份验证 -
1 - 只需添加spring-security maven依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
自动启用基本身份验证,如用户名 - “用户”和密码,您可以使用默认安全密码在控制台中找到 - “bdd42ed9-635d-422b-9430-ce463625fd2e”
2 - 为安全性创建一个配置类,如下面的代码
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authEntryPoint;
@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("user").password("password").roles("USER");
}
}
3 - 另外一种方法是在application.properties文件中添加默认用户名和密码,如下所示
security.user.name=user
security.user.password=password
并创建如下代码的配置类
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
仍然有一些疑问然后点击下面的链接,观看此视频