2015-09-23 78 views
1

目的我的问题是要了解并得到清晰的安全/会话如何在春季工作的图片。因为我对Spring的概念很陌生。 我跟着这个教程了解弹簧安全如何工作

https://spring.io/guides/tutorials/spring-security-and-angular-js/

我的目标是:当某些资源的用户请求(例如/顺序/细节。),如果该请求在头中没有标记,那么它应该被重定向到带有新令牌的登录页面。

@EnableWebSecurity 
@Configuration 
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 
public class Config extends WebSecurityConfigurerAdapter { 

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

     http.httpBasic().and().authorizeRequests().antMatchers("/*") 
       .permitAll().anyRequest().authenticated().and().csrf() 
       .csrfTokenRepository(csrfTokenRepository()).and() 
       .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class); 

    } 

    private Filter csrfHeaderFilter() { 
     return new OncePerRequestFilter() { 
      @Override 
      protected void doFilterInternal(HttpServletRequest request, 
        HttpServletResponse response, FilterChain filterChain) 
        throws ServletException, IOException { 
       CsrfToken csrf = (CsrfToken) request 
         .getAttribute(CsrfToken.class.getName()); 
       if (csrf != null) { 
        Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); 
        String token = csrf.getToken(); 
        if (cookie == null || token != null 
          && !token.equals(cookie.getValue())) { 
         cookie = new Cookie("XSRF-TOKEN", token); 
         cookie.setPath("/"); 
         response.addCookie(cookie); 
         response.sendRedirect("/login"); 
        } 
       } 
       filterChain.doFilter(request, response); 
      } 
     }; 
    } 

    private CsrfTokenRepository csrfTokenRepository() { 
     HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
     repository.setHeaderName("X-XSRF-TOKEN"); 
     return repository; 
    } 
} 

上面的代码工作正常,但关于重定向到登录页面,我无法实现它。

请帮我理解这里的概念。如果你需要更多的细节,请让我知道。

谢谢

+0

你到底想做什么?告诉我。我在这工作了一段时间! –

+0

我正在更新我的代码,请参阅这个 – Roxy

+0

无论您想要实现什么,Spring-Security都已经有机制来实现这一点。我可以说,你让事情变得复杂。请参阅指南并进行配置。另外,请尝试正确解释问题所在。我已经失去了第3段的内容。 –

回答

0

我几个星期前在你的地方。我不得不将安全性融入到春季项目中,并且我对春季和安全都很陌生。 这是我做的。

  1. 通过相当多的安全浏览过的构架
  2. 了解到什么是认证模块的认证模块等
  3. 我碰到KeyCloak来到一点点。我曾与它的1.4版
  4. 在本地安装keycloak并建立
  5. 配置我的keycloak适配器springboot应用领域(你可以找到所有关于它keycloak文档中)
  6. ,就是这样。我能够使用json文件和一个xml配置文件来保护我的web应用程序并保留api。

看看它。 我不是安全或弹簧方面的专家。只是分享我所做的最近的工作。