2014-10-16 24 views

回答

1

如果您不想使用spring-security出於某種原因,並希望讓您的自定義實現僅允許訪問會話存在,那麼您還可以編寫一個實現javax.servlet.Filter的RequestFilter,並檢查請求有一個有效的會話,然後允許它通過其他顯示一個錯誤頁面。這是一個例子。

public class RequestAuthenticationFilter implements Filter { 

    private static final Logger LOG = Logger.getLogger(RequestAuthenticationFilter.class); 

    protected static final List<String> ALLOWED_URL_LIST = Arrays.asList("/login.htm", "/400.htm", "/403.htm", "/404.htm", "/405.htm", "/500.htm", "/503.htm"); 

    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 

    } 

    @Override 
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, 
     ServletException { 

     HttpServletRequest request = (HttpServletRequest) req; 

     HttpSession session = request.getSession(false); 
     String url = (request.getRequestURI()); 

     if(ALLOWED_URL_LIST.contains(url) || url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".png") 
      || url.endsWith(".jpg") || url.endsWith(".jpeg") || url.endsWith(".ttf") || url.endsWith(".woff") 
      || url.endsWith(".csv")) { 

      filterChain.doFilter(request, response); 
     } 
     else if((null == session) || session.getAttribute("user") == null 
      || StringUtils.isEmpty(((User) session.getAttribute("user")).getUsername().trim())) { 

      ((HttpServletResponse) response).sendRedirect("/login.htm"); 
     } 
     else { 
      filterChain.doFilter(request, response); 
     } 
    } 

    @Override 
    public void destroy() { 

    } 
} 

在這個例子中附加檢查,如果請求的是任何圖像,JS,CSS文件,那麼我們跳過會話確認。

一旦添加了過濾器實現,您將不得不接下來確保您想要驗證會話的所有請求都通過此過濾器。爲此,您必須爲此過濾器創建一個bean,然後在您的web.xml中引用該bean。

以下是您必須在web.xml中包含的內容。這裏的是用來爲過濾器創建bean的名稱。並且可以使用來決定要使用此過濾器檢查哪個網址用於會話檢查

<filter> 
    <filter-name>requestAuthenticationFilter</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter> 

<filter-mapping> 
    <filter-name>requestAuthenticationFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 
1

您可以很容易地通過Spring-Security進行設置 - 例如。考慮從Spring安全網站一個例子:

protected void configure(HttpSecurity http) throws Exception { 
    http 
     .authorizeRequests()                 
      .antMatchers("/resources/**", "/signup", "/about").permitAll()     
      .antMatchers("/admin/**").hasRole("ADMIN")          
      .antMatchers("/db/**").access("hasRole('ROLE_ADMIN') and hasRole('ROLE_DBA')") 
      .anyRequest().authenticated()             
      .and() 
     // ... 
     .formLogin(); 
} 

這裏/resources映射路徑是允許每個人(包括匿名用戶),其他一切需要用戶有一定的作用,或者至少在已經登錄

相關問題