首页 文章

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

提问于
浏览
-1

我创建了一个Spring Boot应用程序,我在 /resources/static 文件夹中有我的前端应用程序 .

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

这是我的WebSecurity Configuration类:

@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

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

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

  • 1

    解决问题是最重要的,

    更新

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

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

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

相关问题