2016-06-28 44 views
1

我已經開發了一個Spring安全性的應用程序,並根據用戶角色(如管理員和客戶)登錄,我觀察到它記錄在app/j_spring_security_check中。我想通過身份驗證來實現具有安全性的過濾器並跟蹤所有的URL。請所說的其實是實現如何在spring security中使用過濾器並開發過濾器中的認證

+1

我有什麼實際問題毫無頭緒是。請閱讀http://stackoverflow.com/help/how-to-ask並改進您的問題。 –

+0

春季有趣的話題我給出的解決方案的評論,你可以檢查我希望它可以幫助你。 – Deepanjan

回答

1

Security_configuration.java方式

csrfheaderfilter.java

import java.io.IOException; 

import javax.servlet.FilterChain; 
import javax.servlet.ServletException; 
import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.springframework.security.web.csrf.CsrfToken; 
import org.springframework.web.filter.OncePerRequestFilter; 
import org.springframework.web.util.WebUtils; 

public class CsrfHeaderFilter extends 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, "CSRF-TOKEN"); 
      String token = csrf.getToken(); 
      if (cookie == null || token != null 
        && !token.equals(cookie.getValue())) { 
       cookie = new Cookie("CSRF-CSRF-TOKEN", token); 
       cookie.setPath("/main.html"); 
       cookie.setHttpOnly(true); 
       cookie.setMaxAge(20); 
       response.addCookie(cookie); 

      } 
     } 
     filterChain.doFilter(request, response); 
    } 
} 

csrfrequestmatcher.java

import java.util.regex.Pattern; 

import javax.servlet.http.HttpServletRequest; 

import org.springframework.security.web.util.matcher.RegexRequestMatcher; 
import org.springframework.security.web.util.matcher.RequestMatcher; 

/** 
* 
* The default functionality is to skip CSRF checking for GET method. This 
* functionality is lost when an explicit request matcher is provided. So, need 
* to make sure that GET methods are skipped manually. 
* 
*/ 

public class CsrfRequestMatcher implements RequestMatcher { 

    // Always allow the HTTP GET method 
    private Pattern allowedMethods = Pattern.compile("^GET$"); 
    private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher(
      "/unprotected", null); 

    @Override 
    public boolean matches(HttpServletRequest request) { 

     // Skip checking if request method is a GET 
     if (allowedMethods.matcher(request.getMethod()).matches()) { 
      return false; 
     } 

     // Check CSRF in all other cases. 
     return !unprotectedMatcher.matches(request); 
    } 

} 
+0

感謝您的回覆。我可以知道如何在春季驗證csrf令牌 –

+0

請附上spring-security.xml文件以供參考 –

+0

http://www.mkyong.com/spring-security/spring-security-hello-world-example/請參考此鏈接獲取安全性xml,否則您可以使用maven來管理安全性依賴性。 – Deepanjan