2016-01-08 23 views
2

我正在開發一個春季啓動應用程序,我正在關注這個reply, 它一切正常,儘管需要一些適應,使其在春季啓動工作,但問題是當我撥打:春季開機過濾器不返回正確的迴應

requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); 

返回「404未找到」,而不是「401未授權」,該方法被調用,它捕獲異常,但返回錯誤狀態。

Obs:如果我刪除了過濾器的約束條件,它通常工作。

過濾器:

@Secured 
@Provider 
@Component 
@Priority(Priorities.AUTHENTICATION) 
public class AuthenticationFilter implements ContainerRequestFilter { 

@Override 
public void filter(ContainerRequestContext requestContext) throws IOException { 

    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); 

    if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) { 
     throw new NotAuthorizedException("Authorization header must be provided"); 
    } 

    String token = authorizationHeader.substring("Bearer".length()).trim(); 

    try { 

     validateToken(token); 

    } catch (Exception e) { 
     requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); 
    } 
} 

private void validateToken(String token) throws Exception { 
} 
} 

資源:

@Component 
@Path("/") 
public class Hello { 

@Secured 
@GET 
@Path("/hello") 
public String test() { 
    return "Hello!"; 
} 
@GET 
@Path("/world") 
public String world() { 
    return "World!"; 
} 
} 
+0

嘗試API端點[這一點](http://stackoverflow.com/a/34321347/2587435) –

+0

作品魅力感謝很多,請一個適當的答覆,所以我可以選擇你的答案。 – danillosl

+0

只是把它作爲一個笨蛋關閉它:-)用例可能不一樣,但原因是一樣的。 –

回答

0

我假設你正在使用Jersey API來構建RESTful接口。您收到的404涉及(我認爲)@Path(澤西島)或@RequestMapping(春季)。

如果您發佈了更多與API路徑相關的代碼,那麼我們可以提供更多幫助。

謝謝。

如果您期待頂層路徑@Path("/")。你要再添加斜槓這樣的URI最終會看起來像:

http://localhost.com//hello http://localhost.com//world

爲了解決這個問題,從方法刪除正斜槓@Path註釋和重建。這將導致看起來像

http://localhost.com/hello http://localhost.com/world

+0

這不是問題,兩個端點都在工作,「world」方法正常返回字符串,並且hello被過濾器截獲,問題在於過濾器沒有返回正確的響應,如果我在過濾器上刪除if「你好「的方法正常工作。 (彈簧靴帶或不帶額外的「/」,我剛測試過)。 – danillosl

+0

你能添加相關的過濾器代碼嗎? –

+0

已在問題中。 – danillosl