因此,我有一个包含 REST API 的应用程序,该应用程序由 IOT 设备上的自定义 Java 应用程序使用,无需用户交互。而且我还有一个 Web 应用程序,需要有状态会话来维护用户登录。
是否可以使用 Spring Security 对 API 和 Web 控制器的请求进行不同的身份验证?我应该对 REST API 使用什么形式的身份验证?
实现您所寻找的目标的一种方法是在您的 Spring Security 中拥有 2 个配置。例如。
注意antMatcher
(matcher不是匹配器s). The antMatcher
将控制您的整个配置应用哪一组 url,即FormLoginWebSecurityConfigurerAdapter
下面的示例仅适用于 uri 匹配/api/test/**
。当然,您可以定义antMatcher
仅在其中一个配置中说 config1 ,在这种情况下另一个配置将是一个包罗万象(即捕获与 config1 不匹配的所有内容)
@EnableWebSecurity
@Configuration
public class SecurityConfig {
@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
}
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
http
.antMatcher("/api/v1/**")
.authorizeRequests()
.antMatchers("/api/v1/**").authenticated()
.and()
.httpBasic();
}
}
@Configuration
@Order(2)
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("user").roles("USER");
auth.inMemoryAuthentication().withUser("admin1").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED); // CONFIGURE TYPE OF SESSION POLICY
http
.antMatcher("/api/test/**")
.authorizeRequests()
.antMatchers("/api/test/**").authenticated()
.and()
.formLogin();
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)