解决方法如下:
WebSecurityConfigurerAdapter
。@Configuration
@EnableWebSecurity
public class CustomSecurityFilterChain extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("ADMIN")
.and()
.withUser("user").password("{noop}user").roles("USER");
}
}
在上述示例中,configure(HttpSecurity http)
方法定义了安全过滤器链的配置规则。对于/admin/**
路径,要求用户具有ADMIN
角色;对于/user/**
路径,要求用户具有USER
角色;对于其他所有路径,要求用户进行身份验证。此外,还配置了表单登录和HTTP基本身份验证。
configureGlobal(AuthenticationManagerBuilder auth)
方法用于配置用户的认证信息。在示例中,使用内存认证,创建了两个用户,分别具有ADMIN
和USER
角色。
在主应用程序类中,使用@EnableWebSecurity
注解启用Spring Security,并将自定义的安全过滤器链类添加到Spring的应用程序上下文中。
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
通过以上步骤,我们就创建了一个包含两个.authorizeHttpRequest
的安全过滤器链,并为不同路径配置了不同的访问权限。