【问题标题】:Secure an Angular JS app with Spring Security使用 Spring Security 保护 Angular JS 应用程序
【发布时间】:2017-04-14 19:47:11
【问题描述】:

我创建了一个 Spring Boot 应用程序,我的前端应用程序位于 /resources/static 文件夹中。

对于路由,我使用的是 Angular JS UI 路由器库。 我已经定义了一条路线,我只想让管理员访问它,现在我正在尝试使用 Spring Security 来保护它。

这是我的网络安全配置类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter  {

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .inMemoryAuthentication()
            .withUser("user").password("password").roles("USER").and()
            .withUser("admin").password("password").roles("USER", "ADMIN");
}

  @Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
      httpSecurity
      .authorizeRequests()
      .antMatchers(HttpMethod.GET, "/#/admin").hasRole("ADMIN")
      .and()
      .formLogin()
      .and()
      .authorizeRequests()
      .antMatchers(HttpMethod.POST, "/member", "/member/**").permitAll()
      .antMatchers(
              HttpMethod.GET,
              "/",
              "/*.html",
              "/favicon.ico",
              "/**/*.html",
              "/**/*.css",
              "/**/*.js",
              "/**/**/*.css",
              "/**/**/*.js",
              "/**/**/*.html",
              "/**/**/**/*.css",
              "/**/**/**/*.js",
              "/**/**/**/*.html",
              "/**/**/**/**/*.css",
              "/**/**/**/**/*.js"          
      ).permitAll()
      .antMatchers("/auth/**",  "/member/**", "/account/**").permitAll() 

      .and()
      .csrf().disable();

  }
 }

我试图保护的路由可以通过http://localhost:8080/#/admin 访问。
但是,每当我访问该路由时,都不需要登录,任何人都可以查看该页面。
我应该遵循另一种方法吗?

【问题讨论】:

    标签: java angularjs spring spring-security spring-boot


    【解决方案1】:

    URL:http://localhost:8080/#/admin 映射到permitAll 列表中的/,而不是/#/admin 规则,因为#/admin 部分只是URL 片段,通常不是服务器端的业务。

    您必须在前端和后端之间定义一个 API。通常采用 RESTful Web 服务形式,并服务于/api/* 路径。保护路径,让您的前端仅通过这些 API 与您的后端通信。

    【讨论】:

      【解决方案2】:

      更容易解决您的问题,

      更新

      .antMatchers(HttpMethod.GET, "/#/admin").hasRole("ADMIN")
      

      .antMatchers(HttpMethod.GET, "/#/admin").hasRole("ADMIN").anyRequest().authenticated()
      

      对于每个匹配器,您总是需要permitAll()authenticated()

      【讨论】:

      • 这行得通,但现在我应该登录以访问所有端点,即使它们之前可用
      猜你喜欢
      • 2020-04-06
      • 2019-04-02
      • 1970-01-01
      • 2018-02-22
      • 2011-09-10
      • 2013-11-29
      • 2021-06-25
      • 2019-09-08
      • 2018-11-04
      相关资源
      最近更新 更多