Java – spring rest security – protects different URLs in different ways
•
Java
I use the rest API for basic authentication under spring 4 These rest services are located under / API / V1 / * * URL However, I want to add another set of rest endpoints under different URLs / APIs / V2 / * * but protected with token based authentication
Can I use a servlet to do this? How do I configure spring security to use different forms of authentication for different URLs?
thank you.
Solution
This is a code example in Java configuration. It uses userdetailsservice and provides 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... */
}
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
