失败的HTTP POST请求,因为CORS的 [英] Failed HTTP post request because of CORS

查看:1093
本文介绍了失败的HTTP POST请求,因为CORS的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不设法让我的应用程序运行。我读这个了整整一天,尝试了一堆东西,但最终无济于事的工作。在最后一次尝试我想这链接。我对Java后端作为RESTful Web服务,而不象州或RestEasy的,只是纯java任何额外的框架。在那里,我有我的登录POST方法:

  @POST
@Path(登录)
@Produces(值=应用/ JSON)
市民反应登录(){    AccountAuthentificator authentificator = AccountAuthentificator.getInstance();
    状态状态= Response.Status.OK;    字符串credentialValue = getHeaderValue(AccountAuthentificator.AUTH_CREDENTIALS);
    如果(credentialValue == NULL){
        状态= Response.Status.FORBIDDEN;
        返回WebServiceUtil.createResponse(状态,失踪头帐户凭据。);
    }    尝试{
        LoginResponse解析度= authentificator.login(credentialValue);
        返回WebServiceUtil.createResponse(状态,RES);
    }赶上(的AccessControlException E){
        状态= Response.Status.FORBIDDEN;
        返回WebServiceUtil.createResponse(状态,
                用户不存在,请确认您的用户名和密码。);
    }
}

该WebServiceUtil.createResponse方法基本上添加必要的头,你可以在这里看到:

 公共静态响应createResponse(状态状态,对象responseContent){    ResponseBuilder resBuilder = Response.status(status.getStatus code());    resBuilder.header(访问控制允许原产地,*);
    resBuilder.header(访问控制允许的方法,GET,POST,OPTIONS);
    resBuilder.header(访问控制允许的凭据,真);
    resBuilder.header(访问控制允许报头,原产地,X-要求-着,内容类型,接受授权);    resBuilder.allow(「购股权」);    resBuilder.entity(getJSONAsString(responseContent));    返回resBuilder.build();
}

我也看到人们用另一种方法。这是有过滤器,这样例如 。我也想知道如果我执行与此不同在哪里到底是定义的preflight - 在我实现它是做了.allow(「购股权」),但你可以纠正我的我错了

然后,我有我的web应用程序,我把这个POST方法。我使用这个AngularJS。在我AuthenticateController控制器我有登录的方法,这就是所谓的登录表单提交。实施看起来是这样的:

 功能登录信息(用户名,密码){
        // CreateLoginHeader通过登录值的用户名和密码,创建授权令牌
        VAR的authData = CreateLoginHeader(用户名,密码);
        无功配置= {
                withCredentials:真实,
                标题:{'授权':}的authData
        };
        $ http.post(的http:// XXXX',配置)。然后(SuccessLogin,ErrorLogin);
    }

有谁知道什么是错在这里?通过Chrome开发者工具,我可以看到我的错误XMLHtt prequest无法加载'占位符,服务器的URL响应preflight请求不通过访问控制检查:没有访问控制允许-Origin标头的请求资源present。Origin的占位符的客户端的URL因此不允许访问。

我应该在客户端加入这两个标头值,叫我的后端时:


  • 访问控制请求法

  • 访问控制请求报头


解决方案

Options(选项)请求不是由登录,处理,这样 createResponse 不叫。

有一个看看: https://blogs.oracle.com/theaquarium/entry/supporting_cors_in_jax_rs (你应该实施 javax.ws.rs.container.ContainerResponseFilter ,看到的如何使用JAX-RS与泽西)来处理CORS

另一种可能性为您的code在这里(但如果你开发一个真正的应用程序):添加 @ javax.ws.rs.OPTIONS 你的方法像你这样用 @ javax.ws.rs.POST

I do not manage to get my application running. I was reading about this the whole day, tried a bunch of stuff, but in the end nothing did work. In the last attempt I tried this link. I have the java back end as a RESTful web service without any additional framework like Jersey or RESTeasy, just pure java. There I have my login POST method:

@POST
@Path("login")
@Produces(value = "application/json")
public Response login() {

    AccountAuthentificator authentificator = AccountAuthentificator.getInstance();
    Status status = Response.Status.OK;

    String credentialValue = getHeaderValue(AccountAuthentificator.AUTH_CREDENTIALS);
    if (credentialValue == null) {
        status = Response.Status.FORBIDDEN;
        return WebServiceUtil.createResponse(status, "Missing account credentials in header.");
    }

    try {
        LoginResponse res = authentificator.login(credentialValue);
        return WebServiceUtil.createResponse(status, res);
    } catch (AccessControlException e) {
        status = Response.Status.FORBIDDEN;
        return WebServiceUtil.createResponse(status,
                "User does not exist. Please verify your user name and password.");
    }
}

The WebServiceUtil.createResponse method basically adds the necessary headers as you can see here:

public static Response createResponse(Status status, Object responseContent) {

    ResponseBuilder resBuilder = Response.status(status.getStatusCode());

    resBuilder.header("Access-Control-Allow-Origin", "*");
    resBuilder.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    resBuilder.header("Access-Control-Allow-Credentials", "true");
    resBuilder.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

    resBuilder.allow("OPTIONS");

    resBuilder.entity(getJSONAsString(responseContent));

    return resBuilder.build();
}

I also saw people used another approach. It was with filters, like this example. I was also wondering if my implementation differs from this and where exactly is the preflight defined - in my implementation it is the .allow("OPTIONS") which does that, but you can correct me of I am wrong.

And then I have my web application where I call this POST method. I am using AngularJS for this. In my AuthenticateController controller I have the Login method, which is called on submit in the login form. The implementation looks like this:

function Login(username, password) {
        // CreateLoginHeader creates the authorization token through the login values username and password
        var authdata = CreateLoginHeader(username, password);
        var config = {
                withCredentials: true,
                headers:  { 'Authorization': authdata }
        };
        $http.post('http://XXXX', config).then(SuccessLogin, ErrorLogin);
    }

Does anybody know what is wrong here? Through the chrome developer tools I can see I get the error "XMLHttpRequest cannot load 'placeholder-server-URL'. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'placeholder-client-URL' is therefore not allowed access.".

Should I be adding those two header values on the client side, when calling my back end:

  • Access-Control-Request-Method
  • Access-Control-Request-Headers

解决方案

The Options request is not handled by login, so createResponse is not called.

Have a look at: https://blogs.oracle.com/theaquarium/entry/supporting_cors_in_jax_rs (you should implement a javax.ws.rs.container.ContainerResponseFilter, see How to handle CORS using JAX-RS with Jersey)

Another possibility for your code here (but not if you develop a 'real' application): add @javax.ws.rs.OPTIONS to your method like you did with @javax.ws.rs.POST.

这篇关于失败的HTTP POST请求,因为CORS的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆