CORS选项调用

时间:2019-02-27 13:32:54

标签: rest cors options

我开发了一个react应用程序,该应用程序对端口9000上运行的服务器进行API调用。由于CORS问题,我无法获得对API调用的响应。在服务器中,我启用了访问控制允许源标头,但仍然出现相同的错误。

这是服务器中的REST API代码。

package io.ballerina.messaging.broker.core.rest.api;

import io.ballerina.messaging.broker.auth.BrokerAuthConstants;
import io.ballerina.messaging.broker.auth.authorization.Authorizer;
import io.ballerina.messaging.broker.auth.authorization.enums.ResourceAction;
import io.ballerina.messaging.broker.auth.authorization.enums.ResourceType;
import io.ballerina.messaging.broker.core.BrokerFactory;
import io.ballerina.messaging.broker.core.rest.AuthGrantApiDelegate;
import io.ballerina.messaging.broker.core.rest.BindingsApiDelegate;
import io.ballerina.messaging.broker.core.rest.BrokerAdminService;
import io.ballerina.messaging.broker.core.rest.ExchangesApiDelegate;
import io.ballerina.messaging.broker.core.rest.model.BindingSetInfo;
import io.ballerina.messaging.broker.core.rest.model.ChangeOwnerRequest;
import io.ballerina.messaging.broker.core.rest.model.Error;
import io.ballerina.messaging.broker.core.rest.model.ExchangeCreateRequest;
import io.ballerina.messaging.broker.core.rest.model.ExchangeCreateResponse;
import io.ballerina.messaging.broker.core.rest.model.ExchangeMetadata;
import io.ballerina.messaging.broker.core.rest.model.ResponseMessage;
import io.ballerina.messaging.broker.core.rest.model.UserGroupList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import org.wso2.msf4j.Request;

import javax.security.auth.Subject;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import javax.ws.rs.OPTIONS;

@Path(BrokerAdminService.API_BASE_PATH + "/exchanges")
@Api(description = "the exchanges API")
@Produces({ "application/json" })
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2018-02-16T16:43:30.881+05:30")
public class ExchangesApi {

    private final ExchangesApiDelegate exchangesApiDelegate;
    private final BindingsApiDelegate bindingsApiDelegate;
    private final AuthGrantApiDelegate grantApiDelegate;

    public ExchangesApi(BrokerFactory brokerFactory, Authorizer authorizer) {
        this.exchangesApiDelegate = new ExchangesApiDelegate(brokerFactory, authorizer);
        this.bindingsApiDelegate = new BindingsApiDelegate(brokerFactory);
        this.grantApiDelegate = new AuthGrantApiDelegate(authorizer);
    }

 @GET
    @Produces({ "application/json" })
    @ApiOperation(value = "Get all exchanges", notes = "Retrieves all the exchanges in the broker", response = ExchangeMetadata.class, responseContainer = "List", authorizations = {
            @Authorization(value = "basicAuth")
    }, tags={  })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "List of exchanges", response = ExchangeMetadata.class, responseContainer = "List"),
            @ApiResponse(code = 401, message = "Authentication information is missing or invalid", response = Error.class) })
    public Response getAllExchanges(@Context Request request) {
        return exchangesApiDelegate.getAllExchanges((Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
    }

 @OPTIONS
    @Path("{path : .*}")
    public Response options() {
        return Response.ok("")
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
                .header("Access-Control-Allow-Credentials", "true")
                .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
                .header("Access-Control-Max-Age", "1209600")
                .build();
    }



}


**Here is exchangeApiDelegate.java file**

package io.ballerina.messaging.broker.core.rest;

import io.ballerina.messaging.broker.auth.AuthNotFoundException;
import io.ballerina.messaging.broker.auth.AuthServerException;
import io.ballerina.messaging.broker.auth.authorization.Authorizer;
import io.ballerina.messaging.broker.auth.authorization.authorizer.rdbms.resource.AuthResource;
import io.ballerina.messaging.broker.auth.authorization.enums.ResourceType;
import io.ballerina.messaging.broker.common.ResourceNotFoundException;
import io.ballerina.messaging.broker.common.ValidationException;
import io.ballerina.messaging.broker.core.BrokerAuthException;
import io.ballerina.messaging.broker.core.BrokerAuthNotFoundException;
import io.ballerina.messaging.broker.core.BrokerException;
import io.ballerina.messaging.broker.core.BrokerFactory;
import io.ballerina.messaging.broker.core.Exchange;
import io.ballerina.messaging.broker.core.rest.model.ActionUserGroupsMapping;
import io.ballerina.messaging.broker.core.rest.model.ExchangeCreateRequest;
import io.ballerina.messaging.broker.core.rest.model.ExchangeCreateResponse;
import io.ballerina.messaging.broker.core.rest.model.ExchangeMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.security.auth.Subject;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;

/**
 * Delegate class that handles /exchanges api requests.
 */
public class ExchangesApiDelegate {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExchangesApiDelegate.class);

    public static final String EXCHANGES_API_PATH = "/exchanges";

    private final BrokerFactory brokerFactory;

    private final Authorizer authorizer;

    public ExchangesApiDelegate(BrokerFactory brokerFactory, Authorizer authorizer) {
        this.brokerFactory = brokerFactory;
        this.authorizer = authorizer;
    }



 public Response getAllExchanges(Subject subject) {
        Collection<Exchange> exchangeList;
        List<ExchangeMetadata> exchangeMetadataList;
        try {
            exchangeList = brokerFactory.getBroker(subject).getAllExchanges();
            exchangeMetadataList = new ArrayList<>(exchangeList.size());
            for (Exchange exchange : exchangeList) {
                exchangeMetadataList.add(toExchangeMetadata(exchange));
            }
        } catch (BrokerAuthException e) {
            throw new NotAuthorizedException(e.getMessage(), e);
        } catch (BrokerException e) {
            throw new InternalServerErrorException(e.getMessage(), e);
        }
        return Response.ok().header("Access-Control-Allow-Origin", "http://localhost:3000")
                .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
                .header("Access-Control-Allow-Credentials", "true")
                .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
                .header("Access-Control-Max-Age", "1209600").entity(exchangeMetadataList).build();
    }

这是我收到的回复

常规

请求网址:http://localhost:9090/broker/v1.0/exchanges 请求方法:OPTIONS 状态码:405方法不允许 远程地址:[:: 1]:9090 推荐人政策:降级时不推荐人

响应头

内容编码:gzip 内容长度:48 日期:2019年2月27日星期三18:49:49 +0530 服务器:wso2-http-transport

请求标头

接受: / 接受编码:gzip,deflate,br 接受语言:en-US,en; q = 0.9 访问控制请求标头:授权 访问控制请求方法:GET 连接:保持活动状态 主机:localhost:9090 来源:http://localhost:3000 用户代理:Mozilla / 5.0(X11; Linux x86_64)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 69.0.3497.81 Safari / 537.36

0 个答案:

没有答案