【发布时间】:2019-06-26 11:51:45
【问题描述】:
首先,为您可能犯的语法错误道歉。我的英语不是很好。
我是 Spring 新手,我正在尝试创建 Basic Auth 安全性。
我正在尝试配置一个端点具有公共访问权限,而其他端点管理用户访问权限。
这是我的想法:
localhost:8080/api/teacher/findAll -> 公共访问
localhost:8080/api/teacher/admin/findAll -> 只有管理员权限
localhost:8080/api/teacher/user/findAll -> 仅限用户访问
这是我的代码:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("user").roles("USER")
.and().withUser("admin").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/teacher/findAll").permitAll()
.antMatchers("/teacher/admin/findAll").hasRole("ADMIN")
.antMatchers("/teacher/user/findAll").hasRole("USER")
.antMatchers("*/create/**").hasRole("ADMIN")
.and().httpBasic();
}
@SuppressWarnings("deprecation")
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
【问题讨论】:
-
您可以拥有一个端点并根据当前登录用户的角色执行必要的逻辑。不需要 3 个端点。
标签: java spring spring-boot spring-security