问题描述
我在Spring 4下使用基本身份验证工作REST API。这些REST服务位于/ api / v1 / ** URL下。但是,我想在不同的url / api / v2 / **下添加另一组REST端点,但是使用基于令牌的身份验证进行保护。
I have working REST API under Spring 4 using Basic authentication. These REST services are under /api/v1/** URL. However, I want to add another set of REST endpoints under different url /api/v2/**, but protected with token-based authentication.
是否可以执行这有一个servlet?如何配置Spring Security对不同的URL使用不同形式的身份验证?
Is it possible to do this with one servlet ? How to configure Spring Security to use different forms of authentication for different URLs ?
谢谢。
推荐答案
以下是Java配置中使用 UserDetailsService
的代码示例,并针对不同的URL端点具有不同的安全配置:
Here's a code sample in Java config that uses UserDetailsService
and has different security configurations for different URL endpoints:
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Configuration
@Order(1)
public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/v1/**")
.httpBasic()
.realmName("API")
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/v1/**").authenticated();
}
}
@Configuration
@Order(2)
public static class ApiTokenSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/v2/**")
/* other config options go here... */
}
}
}
这篇关于Spring REST安全性 - 以不同方式保护不同的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!