2012-09-16 19 views
2

簡短版本:當我使用自定義身份驗證篩選器時,如何讓HttpServletRequest.getRemoteUser()返回用戶名?使用自定義身份驗證篩選器時使用getRemoteUser()訪問用戶名

龍版本:

我修改目前使用的聲明性安全(web.xml中&的tomcat-users.xml中),而不是使用自定義(由我寫的)認證過濾器Tomcat應用程序(從衍生的javax。 servlet.Filter)。有很多關於如何做到這一點的信息,它看起來非常簡單。

但是,現有的應用程序調用HttpServletRequest.getRemoteUser(),我假設除非我在過濾器中設置此屬性,否則它將返回null。我無法找到有關如何在篩選器中填充getRemoteUser()媒體資源的任何信息(沒有setRemoteUser())。我找到了一個post out there,建議將請求對象包裝在過濾器中。如果必須的話,我會這樣做,但我希望有一種侵略性較小的方法來實現這一點。

任何人都可以幫忙嗎?

回答

2

是的,修改HttpServletRequestHttpServletResponse的唯一方法是修飾它,並通過覆蓋它們來爲感興趣的方法提供自己的實現。這是一個帶有認證過濾器的標準模式,這就是HttpServletRequestWrapper(響應對象是HttpServletResponseWrapper)的用途。我們這樣做,以包裝kerberized請求,如下

public class KerbHttpServletRequest extends HttpServletRequestWrapper 
{ 
    private Principal myPrincipal; 
    private String myAuthType; 

    public KerbHttpServletRequest(HttpServletRequest aRequest, 
     Principal aPrincipal, 
     String aAuthType) 
    { 
     super(aRequest); 
     myPrincipal = aPrincipal; 
     myAuthType = aAuthType; 
    } 

    /** 
    * This method returns the Remote User name as user\@domain.com. 
    */ 
    @Override 
    public String getRemoteUser() 
    { 
     return myPrincipal.getName(); 
    } 

    @Override 
    public String getAuthType() 
    { 
     return myAuthType; 
    } 

    @Override 
    public Principal getUserPrincipal() 
    { 
     return myPrincipal; 
    } 
} 
+0

謝謝,看起來很容易。子問題:我看到你創建一個'Principal'並覆蓋'getUserPrincipal()'。我們在這個應用程序中不使用'Principal'。如果我們不覆蓋'getUserPincipal()'並且只覆蓋'getRemoteUser()',我會在什麼地方分手? –

+0

不,你不會(這是我的Kerberos身份驗證的具體情況)。所有你感興趣的是getRemoteUser(),只要你返回你通過運行認證協議推導出的值,這就足夠了(再次假設'HttpServletRequest'的所有客戶端都使用getRemoteUser()來獲得用戶登錄)。 – Vikdor

相關問題