【问题标题】:Spring Security: Allow a public endpoint and not allow other endpointsSpring Security:允许公共端点,不允许其他端点
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 2022-10-24
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    相关资源
    最近更新 更多