0
私はthisチュートリアルを試してみましたが、この例で示したようにProviderクラスを実装しました。JAX-RSプロバイダのフィルタメソッドが呼び出されることはありません
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
}
も注釈付き:私は、注釈のためのインタフェースを作成し
Dez 25, 2017 6:47:09 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFORMATION: Root resource classes found:
class com.jwt.service.AuthenticationEndpoint
class com.jwt.service.HelloWorldService
Dez 25, 2017 6:47:09 PM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFORMATION: Provider classes found:
class com.jwt.service.AuthenticationFilter
:
@Provider
@Secured
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
private static final String REALM = "example";
private static final String AUTHENTICATION_SCHEME = "Bearer";
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the Authorization header from the request
String authorizationHeader =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Validate the Authorization header
if (!isTokenBasedAuthentication(authorizationHeader)) {
abortWithUnauthorized(requestContext);
return;
}
// Extract the token from the Authorization header
String token = authorizationHeader
.substring(AUTHENTICATION_SCHEME.length()).trim();
try {
// Validate the token
validateToken(token);
} catch (Exception e) {
abortWithUnauthorized(requestContext);
}
}
private boolean isTokenBasedAuthentication(String authorizationHeader) {
// Check if the Authorization header is valid
// It must not be null and must be prefixed with "Bearer" plus a whitespace
// The authentication scheme comparison must be case-insensitive
return authorizationHeader != null && authorizationHeader.toLowerCase()
.startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
}
private void abortWithUnauthorized(ContainerRequestContext requestContext) {
// Abort the filter chain with a 401 status code response
// The WWW-Authenticate header is sent along with the response
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE,
AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
.build());
}
private void validateToken(String token) throws Exception {
// Check if the token was issued by the server and if it's not expired
// Throw an Exception if the token is invalid
//TODO validate against database
if(!token.equals("exampleString")) {
throw new AuthenticationException("Invalid token.");
}
}
}
このProviderクラスはまた、ログで見ることができ、サーバによって認識されています私のRESTエンドポイント。
私のProviderクラスは認識されますが、注釈付きメソッドが呼び出されたときでも何もしません。認証されていないステータスコードを出力する代わりに、認証が送信されていなくても、 "Secured getUser is called"が返されます。
誰かが、私のProviderクラスのフィルタメソッドが呼び出されない理由を知っていますか?
'com.sun.jersey.api'パッケージはジャージー1です。チュートリアルでは、ジャージー2を扱っています。ジャージー2にアップグレードするか、ジャージー1のソリューションを見つけてください。 – Rouliboy
ジャージー2を実装するためにプロジェクトを変更した後は、今働いて、ありがとう! :) – Fynn
素晴らしい!私は同じ問題を抱えている人を助けるための答えを加えました。 – Rouliboy