java - Spring 安全: Allow a public endpoint and not allow other endpoints

标签 java spring spring-boot spring-security

首先,对您可能犯的语法错误表示歉意。我的英语不是很好。

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

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

这是我的想法:

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

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

最佳答案

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

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

2) localhost:8080/api/teacher/admin/findAll -> 仅管理员访问

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

那么你的配置方法会像这样:

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

关于java - Spring 安全: Allow a public endpoint and not allow other endpoints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56772159/

相关文章:

java - 如何为Android构建一个java代码库?

java - 通过 JAX-RS 客户端支持 HTTP/1.1 和 HTTP/2

java - 部署期间无法使用 weblogic12 中的 spring 模式文档读取 spring beans xml

multithreading - 在多线程上下文中使用 OAuth2RestTemplate

java - 为什么我的spring boot应用会自动关闭?

具有已知池大小但未知工作人员的 Java- FixedThreadPool

java - 无法将java ee spring项目连接到mysql

java - 如何在一个jsp页面引用另一个jsp页面?

java - Gradle 无法构建具有 Docker 依赖项的 JAR

java - 如何预先声明一个数组?