Spring Security:允许公共端点,不允许其他端点

时间:2019-06-26 11:51:45

标签: java spring spring-boot spring-security

首先,为可能出现的语法错误道歉。我的英语不太好。

我是Spring的新手,我正在尝试创建基本身份验证安全性。

我正在尝试配置一个端点具有公共访问权限,而其他端点则管理用户访问权限。

这是我的主意

localhost:8080 / api / teacher / findAll->公共访问

localhost:8080 / api / teacher / admin / findAll->仅ADMIN访问权限

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();
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试创建以下端点:

1)localhost:8080 / api / teacher / all / findAll->公共访问权限

2)localhost:8080 / api / teacher / admin / findAll->仅ADMIN访问权限

3)localhost:8080 / api / teacher / user / findAll->仅用户访问权限

然后您的configure方法将如下:

 @Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
    .antMatchers("/teacher/all/**").permitAll()
    .antMatchers("/teacher/admin/**","*/create/**").hasRole("ADMIN")
    .antMatchers("/teacher/user/**").hasRole("USER")
    .and().httpBasic();
}