当不在ResourceServerConfiguration类中时,Spring Boot RequestMapping URL受保护

时间:2019-11-21 10:01:53

标签: spring-boot spring-security

我已经开始使用以下文件来使用Spring Security和OAuth2配置URL和受保护的路径:

@EnableResourceServer
@RestController
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
{
      @RequestMapping("/publica")
      public String publico() {
        return "Pagina Publica";
      }

      @RequestMapping("/privada")
      public String privada() {
        return "Pagina Privada";
      }

      @RequestMapping("/admin")
      public String admin() {
        return "Pagina Administrador";
      }

      @Override
        public void configure(HttpSecurity http) throws Exception {

            http
                .authorizeRequests().antMatchers("/oauth/token", "/oauth/authorize**", "/publica").permitAll();

            http
                .requestMatchers().antMatchers("/privada")
                .and().authorizeRequests()
                .antMatchers("/privada").access("hasRole('USER')")
                .and().requestMatchers().antMatchers("/admin")
                .and().authorizeRequests()
                .antMatchers("/admin").access("hasRole('ADMIN')");
        }   

}

这很好。如果我尝试在邮递员中访问/privada,则会返回401。

但是,对于我打算以此为基础构建的应用程序,我认为最好在自己的控制器(例如FundsController,UsersController,ProductsController等)中组织网址

因此,作为上述基础示例,我将路径映射方法移至BasicController中:

@RestController
public class BasicController
{
    @RequestMapping("/publica")
    public String publico() {
        return "Pagina Publica";
    }

    @RequestMapping("/privada")
    public String privada() {
        return "Pagina Privada";
    }

    @RequestMapping("/admin")
    public String admin() {
        return "Pagina Administrador";
    }
}

但是将安全性留在ResourceServerConfiguration中:

@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
{

      @Override
        public void configure(HttpSecurity http) throws Exception {

            http
                .authorizeRequests().antMatchers("/oauth/token", "/oauth/authorize**", "/publica").permitAll();

            http
                .requestMatchers().antMatchers("/privada")
                .and().authorizeRequests()
                .antMatchers("/privada").access("hasRole('USER')")
                .and().requestMatchers().antMatchers("/admin")
                .and().authorizeRequests()
                .antMatchers("/admin").access("hasRole('ADMIN')");
        }   

}

但是,现在当我重新启动应用程序(销毁了内存中的访问令牌)然后转到/privada时,它返回了Pagina Privada,这是西班牙语,我认为是“私人页面” :)没有访问令牌无论如何都需要,这不是我想要的。当它都在同一个类中时,它应该像以前一样返回401。我哪里出问题了?

2 个答案:

答案 0 :(得分:0)

添加

@Configuration
@EnableWebSecurity

ResourceServerConfiguration类的注释和 扩展WebSecurityConfigurerAdapter而不是ResourceServerConfigurerAdapter

答案 1 :(得分:0)

您需要在您要覆盖的configure方法中包含以下内容

.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/context"))

.antMatchers("/context/**").fullyAuthenticated();