2016-09-06 1 views
0

基本認証を使用して単純なJersey RESTエンドポイントを埋め込みJettyで実行し、他のWebアプリケーションからのajaxコールを使用してアクセスしようとします。しかし、401 Unauthorizedは、Access-Control-Allow- *ヘッダーが存在する場合でも、プリフライト要求になります。別の原点からURLにアクセスするには? AccessControl-Allow- *ヘッダーが存在する場合でも、プリフライトリクエストは401を返す

Serverコード:

public final class RESTServerStarter { 
private static final int WEB_SERVER_PORT = 8888; 

public static void main(String[] args) throws Exception { 
    final ServletHolder sh = new ServletHolder(ServletContainer.class); 
    sh.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS, PackagesResourceConfig.class.getCanonicalName()); 
    sh.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, HelloRESTService.class.getPackage().getName()); 

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); 
    context.setSecurityHandler(basicAuth("admin", "adminpwd", "Private!")); 
    context.setContextPath("/rest"); 
    context.addServlet(sh, "/*"); 
    context.addFilter(MyFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); 

    final Server server = new Server(); 

    final ServerConnector connector = new ServerConnector(server); 
    connector.setHost("172.18.133.20"); 
    connector.setPort(WEB_SERVER_PORT); 
    server.addConnector(connector); 

    server.setHandler(context); 

    try { 
     server.start(); 
     server.join(); 
    } finally { 
     server.destroy(); 
    } 

} 

private static final SecurityHandler basicAuth(String username, String password, String realm) { 

    HashLoginService hashLoginService = new HashLoginService(); 
    hashLoginService.putUser(username, Credential.getCredential(password), new String[]{"user"}); 
    hashLoginService.setName(realm); 

    Constraint constraint = new Constraint(); 
    constraint.setName(Constraint.__BASIC_AUTH); 
    constraint.setRoles(new String[]{"user"}); 
    constraint.setAuthenticate(true); 

    ConstraintMapping cm = new ConstraintMapping(); 
    cm.setConstraint(constraint); 
    cm.setPathSpec("/*"); 

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler(); 
    csh.setAuthenticator(new BasicAuthenticator()); 
    csh.setRealmName("myrealm"); 
    csh.addConstraintMapping(cm); 
    csh.setLoginService(hashLoginService); 

    return csh; 

} 

public static final class MyFilter implements Filter { 
    public void init(FilterConfig filterConfig) { 
     //nothing to init 
    } 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
     final HttpServletResponse httpResponse = (HttpServletResponse) response; 
     httpResponse.addHeader("Access-Control-Allow-Origin", "http://172.18.133.20:" + RESTClientStarter.WEB_SERVER_PORT); 
     httpResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE, PUT"); 
     httpResponse.addHeader("Access-Control-Allow-Credentials", "true"); 
     httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); 
     chain.doFilter(request, response); 
    } 

    public void destroy() { 
     //nothing to destroy 
    } 
} 

@Path("/test") 
public static class HelloRESTService { 

    @GET 
    @Path("hello") 
    @Produces(MediaType.TEXT_PLAIN) 
    public String hello() { 
     return "hello"; 
    } 
} 

}

クライアントコード:

$(function(){ 
    $.ajax({ 
     url : "http://172.18.133.20:8888/rest/test/hello", 
     type : "GET", 
     timeout : 120000, 
     async : true, 
     xhrFields: { 
      withCredentials: true 
     }, 
     crossDomain: true, 
     headers: { 
      "Authorization": "Basic " + btoa("admin:adminpwd") 
     }, 
     error: function(xhr, status, error) { 
      $("#container").text(error); 
     }, 
     success: function(xhr) { 
      $("#container").text(xhr); 
     } 
    }); 
}); 

ここhttp://172.18.133.20:9999

上のクライアントコードの実行がいっぱいのソースです:

https://bitbucket.org/dmitry_apanasevich/cors/src

教えていただけませんか?

ありがとうございました!

答えて

0

私はSecurityMappingからのOPTIONS要求を除くproblenを解決しました。ただ、1行追加:「、あなたは(「アクセス制御 - 許可 - 起源」をhttpResponse.addHeaderを試してみてください、

... 
ConstraintMapping cm = new ConstraintMapping(); 
cm.setMethod("GET"); //new line 
cm.setConstraint(constraint); 
cm.setPathSpec("/*"); 
... 
0

あなたはhttpResponse.addHeader( "Access-Control-Allow-Origin"、 "http://172.18.133.20:" + RESTClientStarter.WEB_SERVER_PORT)を使用すると思います。残りのアプリの とWEB_SERVER_PORTは9999なので、httpResponseはhttp://172.18.133.20:9999を許可します。 しかし、これはポート8888で呼び出されますが、これは許可されていません。

+0

番号RESTアプリは8888ポートで実行され、クライアントアプリだから9999ポート –

+0

上で実行されているが、HTTP ://172.18.133.20 "); httpResponse.addHeader( "Access-Control-Allow-Origin"、 "http://172.18.133.20:" + RESTClientStarter.WEB_SERVER_PORT)の代わりに。 – Numb

+0

なぜですか? ajax reuestの起源はhttp://172.18.133.20:9999です。私はあなたの決定を試みましたが、うまくいきません。 –

関連する問題