2014-02-14 60 views
2

我一直在RESTlet 2.1項目中工作。我已經想出瞭如何爲我的資源設置身份驗證。事實是..不是所有的人都需要認證!我很困惑我該怎麼做纔對。Restelet路由:有些資源需要認證,有些則不需要。怎麼做?

在下面的代碼,你可以看到我的服務器應用程序的輪廓,特別是「創建入根」:

@Override 
public Restlet createInboundRoot(){ 

    /* the structure so far is: a filter, followed by an authenticator, 
     followed by a rooter. 
     The filter is returned at end of the method. 
    */ 


    //Init filter: 
    SomeFilter someFilter = new SomeFilter(); 


      //Init authenticator: 
    ChallengeAuthenticator authenticator = new ChallengeAuthenticator(
     ......); 
    //more authenticator stuff goes here....   


    //Init router: 
    Router router = new Router(getContext()); 
    //this should be a public resource, no need for auth: 
    router.attach("/0.1/getResource", SomeResource.class) 
    //this is a private resource, needs auth: 
    router.attach("/0.1/getPrivateResource", PrivateResource.class); 

    //set up the flow: filter -> authenticator -> router 
    authenticator.setNext(router);  
    someFilter.setNext(authenticator); 
    return someFilter; 

} 

的過濾器必須是之前的一切,因爲我需要修改都有些頭包。在過濾器之後,我想設置一個分支,我的公共資源的請求只被路由到資源類,並且私有資源的請求必須通過認證者。

我該如何做到這一點?我對這個框架並不熟悉,即使看起來很簡單,也無法弄清楚。

回答

0

我已經想出了完整的解決方案,這是關於「URI模板」。缺少的一件事是路由器可以匹配uri的不同方式,事實上,問題需要「匹配URI的第一部分」這種方法。

/* 
    * Routing structure: 
    * 
    *       ---/public---->(publicR()----> Public Resources 
    * (Filter()---->(routerPP()--| 
    *       ---/private--->(authenticator()---->(privateR()---> Private Resources 
    *  
    */ 

其中routerPP採取的決定,如果URL以/公/或私有開始:

Router routerPP = new Router(getContext()); 
    routerPP.setDefaultMatchingMode(Template.MODE_STARTS_WITH); 
    routerPP.attach("/private", authenticator); 
    routerPP.attach("/public", publicR); 

的一個特殊性在於,後一個URL「通過」路由器,它失去匹配的URL的一部分,因此隨後的路由器(例如公衆一個)將具有這樣的結構:

Router publicR = new Router(getContext()); 
    publicR.attach("/somePublicResource", SomePublicResource.class); 

和這樣的結構下面的URL相匹配: http://somehost.com/public/somePublicResource

如果在第二個路由器您添加「/公/」令牌再次,你會得到一個「資源未找到」錯誤,然後資源將是對:http://somehost.com/public/public/somePublicResource

所以路由器的比賽,並從網址中移除。

參考有關路由和URI匹配我發現有用的是:

http://restlet-discuss.1400322.n2.nabble.com/Trying-to-route-to-two-routes-that-start-with-same-prefix-td7019794.html

http://restlet.org/learn/javadocs/snapshot/jse/api/org/restlet/routing/Router.html

2

想想你的路由器就像一個鏈。你是這樣的:

someFilter - >認證 - >路由器 - >(SomeResource.class | PrivateResource.class)

這意味着所有請求在someFilter開始,經過認證,擊中了路由器,並最終在SomeResource或PrivateResource。

你需要把認證在PrivateResource面前只,移動認證的鏈條的該位,所以它看起來更像是這樣的:

someFilter - >路由器 - >(SomeResource.class |認證 - > PrivateResource.class)

的代碼可能看起來像:

ChallengeAuthenticator authenticator = new ChallengeAuthenticator(......); 
    authenticator.setNext(PrivateResource.class); 
    router.attach("/0.1/getPrivateResource", authenticator); 

這是否幫助?

+0

是有幫助,謝謝。儘管我有很多這兩種類型的資源,所以我認爲我需要兩個以上的路由器,路由器可以匹配url中的正則表達式還是部分url? –

+0

我想你可以鏈路由器。 – tom

相關問題