以下是一个使用Spring Security的示例代码,演示如何使用antMatchers来允许管理员访问所有路由,而其他角色受到限制。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}password").roles("ADMIN")
.and()
.withUser("user").password("{noop}password").roles("USER");
}
}
在上述示例中,我们配置了一个基于内存的认证机制,有两个用户:一个具有ADMIN角色的管理员用户和一个具有USER角色的普通用户。
在configure()方法中,我们使用antMatchers("/admin/**").hasRole("ADMIN")配置了一个规则,允许具有ADMIN角色的用户访问以/admin/开头的所有路由。对于其他没有匹配规则的路由,我们使用anyRequest().authenticated()要求用户进行身份验证。
最后,我们还配置了一个简单的表单登录和基本的HTTP身份验证。
请注意,示例中的密码使用了{noop}前缀,这是为了告诉Spring Security使用不加密的原始密码。在实际应用中,应该使用适当的密码加密算法来存储和验证密码。