У меня есть
HttpServer server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(port), 0);
к которому я пытаюсь прикрутить BasicAuthenticator
HttpContext context = server.createContext("/rpc", new RpcHandler());
context.setAuthenticator(new BasicAuthenticator("rpc") {
@Override
public boolean checkCredentials(String user, String pwd) {
return user.equals("admin") && pwd.equals("password");
}
});
server.setExecutor(Executors.newCachedThreadPool());
server.start();
также к нему хендлер:
class RpcHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
StringBuilder query = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(httpExchange.getRequestBody(), "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
query.append(line);
}
JSONRPC2Response response;
JSONRPC2Request request = null;
try {
if (query == null) {
throw new JSONRPC2ParseException(null);
} else {
request = JSONRPC2Request.parse(query.toString());
if (request.getMethod().startsWith("update_metadata")) {
response = updateMetadata(request);
} else if (request.getMethod().equals("topics_lag_timestamp")) {
response = getTopicLagHandler(request);
} else {
response = new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, request.getID());
}
}
} catch (JSONRPC2ParseException e) {
response = new JSONRPC2Response(JSONRPC2Error.PARSE_ERROR, null);
} catch (NullPointerException e) {
response = new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, null);
}
httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS, HEAD, PUT, POST");
httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type");
httpExchange.getResponseHeaders().add("Access-Control-Max-Age", "86400");
OutputStream outputStream = httpExchange.getResponseBody();
httpExchange.sendResponseHeaders(200, response.toJSONString().length());
outputStream.write(response.toJSONString().getBytes());
outputStream.close();
}
}
При обращении через Postman с header
Authorization: Basic YWRtaW46cGFzc3dvcmQ=
Все работает отлично.
Но при обращении из другого сервиса (фронт на Angular)
@Component({
selector: 'app-lag-timestamp-postgres',
templateUrl: './lag-timestamp.component.html',
styleUrls: ['./lag-timestamp.component.css']
})
export class LagTimestampPGComponent implements OnInit {
url = 'https://localhost:9099/rpc';
response: any;
lagTimestamps: LagsArray;
constructor(public http: HttpClient) {
this.getLagTimestamp();
}
ngOnInit(): void {
this.getLagTimestamp();
}
getLagTimestamp() {
const headers = { 'Authorization': 'Basic YWRtaW46cGFzc3dvcmQ='};
this.response = this.http.post(this.url, '{"method":"topics_lag_timestamp","id":"req-id-01","jsonrpc":"2.0"}',
{headers})
.subscribe((response) => {
this.response = response;
this.lagTimestamps = Object.setPrototypeOf(this.response, Array<LagTimestampObject>());
console.log(this.lagTimestamps);
});
}
}
я получаю ошибку:
Access to XMLHttpRequest at 'http://localhost:9099/rpc' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Если убрать HttpContext и аутентификацию, все работает нормально.
Как устранить эту проблему? И где она вообще кроется, на стороне сервиса-фронта (Angular) или на стороне HttpServer?
httpExchange.getRequestMethod()
и обрабатывайте OPTIONS запрос в соответствии с правилами CORS.