Spring REST 安全性 - 以不同方式保护不同的 URL [英] Spring REST security - Secure different URLs differently
问题描述
我在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!