使用Spring Security保护Angular JS应用程序

时间:2016-11-30 13:06:40

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

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

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

这是我的WebSecurity配置类:

@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访问  但是,每当我访问该路线时,都不会请求登录,任何人都可以查看该页面 我应该遵循另一种方法吗?

2 个答案:

答案 0 :(得分:1)

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

您必须在前端和后端之间定义 API 。通常在RESTful Web服务表单中,并在/api/*路径上提供服务。保护路径,让您的前端仅通过这些API与您的后端通信。

答案 1 :(得分:0)

解决问题是明白的,

更新

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

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

对于每个匹配器,您始终需要permitAll()authenticated()

相关问题