Not using port in the url - spring-boot

I use spring boot (tomcat embedded) and ssl.
Actually, I need to type the port (8443) in the url to be able to access web applicaiton.
How to be able to use domnain name only?
Something like
https://www.bob.com
instead of
https://www.bob.com:8443/
Edit
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat
= new TomcatEmbeddedServletContainerFactory() {
#Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(createHttpConnector());
return tomcat;
}
private Connector createHttpConnector() {
Connector connector
= new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setSecure(false);
connector.setPort(8080);
connector.setRedirectPort(8443);
return connector;
}
now not need to type port
but if it type bob.com, browser convert to
bob.com:8443

Default port used by browsers for HTTP is 80 and HTTPS is 443. If you run your application on 443 (since you are using HTTPS), you don't have to use the port number, browser will automatically reroute your URL. To change the port number in you spring-boot applicatioN specify server.port property in bootstrap.yml.
server:
port: 443

Do you mean something like this?
String webPort = System.getenv("PORT");
if(webPort == null || webPort.isEmpty()) {
webPort = "8080";
}

Related

Change port number in netflix ribbon

I have two services. One runs on port 8001 and it registered in eureka server, other runs on port 8002, and doesn't exist in eureka. I want to change port 8001 to 8002 in my local ribbon client. I have created
public class LocalProxy <T extends DiscoveryEnabledServer> implements ServerListFilter<T>
with method
public List<T> getFilteredListOfServers(List<T> servers)
But I don't know how to change the port. DiscoveryEnabledServer.setPort doesn't work.
Ugly, but it works for me.
private void addProxyRoute(List<T> servers) {
DiscoveryEnabledServer service = findFirst(servers,
s -> "service1".equalsIgnoreCase(s.getInstanceInfo().getAppName()));
if (service == null) return;
IClientConfig clientConfig = new DefaultClientConfigImpl();
DomainExtractingServerList list =
new DomainExtractingServerList(createServer(service.getInstanceInfo()), clientConfig, true);
servers.addAll((Collection<? extends T>) list.getUpdatedListOfServers());
servers.remove(service);
}
private StaticServerList createServer(InstanceInfo app) {
DiscoveryEnabledServer server = new DiscoveryEnabledServer(InstanceInfo.Builder.newBuilder()
.setAppName("service1")
.setPort(8002)
.setHostName(app.getHostName())
.setMetadata(new HashMap<>())
.build(), false, true);
server.setAlive(true);
server.setReadyToServe(true);
return new StaticServerList(server);
}

use spring boot data redis Connect to the redis cluster problem

I used spring boot data redis to connect to the redis cluster, using version 2.1.3 The configuration is as follows:
#Bean
#Primary
public RedisConnectionFactory myLettuceConnectionFactory(GenericObjectPoolConfig poolConfig) {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
final List<String> nodeList = redisProperties.getCluster().getNodes();
Set<RedisNode> nodes = new HashSet<RedisNode>();
for (String ipPort : nodeList) {
String[] ipAndPort = ipPort.split(":");
nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
}
redisClusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
redisClusterConfiguration.setClusterNodes(nodes);
redisClusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
.commandTimeout(redisProperties.getTimeout())
.poolConfig(poolConfig)
.build();
RedisClusterClient clusterClient ;
LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClusterConfiguration,clientConfig);
return factory;
}
However, during the operation, a WARN exception message will always be received as follows:
Well, this seems to be a problem with lettuce, How to map remote host & port to localhost using Lettuce,but I don't know how to use it in spring boot data redis. Any solution is welcome, thank you
I've got the answer, so let's define a ClinentRourse like this:
MappingSocketAddressResolver resolver = MappingSocketAddressResolver.create(DnsResolvers.UNRESOLVED ,
hostAndPort -> {
if(hostAndPort.getHostText().startsWith("172.31")){
return HostAndPort.of(ipStr, hostAndPort.getPort());
}
return hostAndPort;
});
ClientResources clientResources = ClientResources.builder()
.socketAddressResolver(resolver)
.build();
Then through LettuceClientConfiguration.clientResources method set in, the normal work of the lettuce.

Can my Spring Boot application run HTTPS only on certain #RequestMappings?

I'm working on a Spring application that is for a smart house. I got the micro-controllers that send data to the Spring application, but I can not implement SSL on them on account of not enough space and processing speed.
On the client-side, I want to use HTTPS, because the client runs on Android.
Can I map certain requests to HTTP and others to HTTPS?
Can we not open two ports from the spring boot application one on 443 other on 80. So that, on https it listens to 443 and on http to 80. So in your app you can configure http on a url to use 80 port and https to use 443 port.
We can do this by, changes in application.properties:
#Https settings
server.port=443
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password = secret
server.ssl.key-password = secret
#Http setting
server.http.port=80
I am giving an example using Undertow server, you can do this on any application server (tomcat, etc):
#SpringBootApplication
public class Boot {
#Value("${server.http.port:0}")
private Integer httpPort;
public static void main(String[] args) throws Exception {
SpringApplication.run(Boot.class, args);
}
#Bean
public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() {
UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();
factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {
public void customize(Builder builder) {
// worker options
builder.setWorkerThreads(500);
builder.setWorkerOption(Options.TCP_NODELAY, true);
// io options
builder.setIoThreads(Runtime.getRuntime().availableProcessors() * 2);
// socket options
builder.setSocketOption(Options.BACKLOG, 10000);
builder.setSocketOption(Options.TCP_NODELAY, true);
builder.setSocketOption(Options.REUSE_ADDRESSES, true);
// server options
builder.setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, false);
builder.setServerOption(UndertowOptions.ALWAYS_SET_DATE, true);
builder.setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, false);
// Done to keep both http and https port open at production
if (httpPort > 0)
builder.addHttpListener(httpPort, "0.0.0.0");
}
});
return factory;
}
}

HTTP2C (cleartext) client to HTTP2C server

I have an HTTP2C Embedded Jetty 9.x Server running ... note the server connector shows h2c ...
2016-03-21 09:25:44.082:INFO:oejs.ServerConnector:main: Started ServerConnector#66c7bd3f{HTTP/1.1,[http/1.1, h2c, h2c-17, h2c-16, h2c-15, h2c-14]}{0.0.0.0:8080}
I have an OkHttpClient 3 attempting to talk HTTP2C to this server , however it always gets downgraded to HTTP/1.1, what am I missing? Which Java client API supports HTTP2C? My client code is as below ...
package http2;
import java.util.Collections;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GetClear {
public static void main(String[] args) throws Exception {
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();
OkHttpClient client = new OkHttpClient.Builder().connectionSpecs(Collections.singletonList(spec)).build();
Request request = new Request.Builder().url("http://localhost:8080/test").build();
Response response = client.newCall(request).execute();
System.out.println (response.body().string());
System.out.println("****");
response.body().close();
}
}
[The server prints the 'request.getProtocol' from a Jetty servlet and that shows HTTP/1.1 instead of HTTP/2].
HTTP/2 server and client on TLS works just fine using HTTP/2(client code and server code are different of course).
Any help will be truly appreciated.
Using a Jetty HTTP2C client, the same server code works. I guess OkHTTPClient does not support HTTP2C.
A complete h2c example using the HelloHandler example from the jetty doc:
public class HelloServer {
public static class HelloHandler extends AbstractHandler {
final String greeting;
final String body;
public HelloHandler() {
this("Hello World");
}
public HelloHandler(String greeting) {
this(greeting, null);
}
public HelloHandler(String greeting, String body) {
this.greeting = greeting;
this.body = body;
}
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
response.setContentType("text/html; charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("<h1>" + greeting + "</h1>");
if (body != null) {
out.println(body);
}
baseRequest.setHandled(true);
}
}
public static void main(String[] args) throws Exception {
Server server = new Server();
server.setHandler(new HelloHandler());
HttpConfiguration httpConfig = new HttpConfiguration();
ConnectionFactory h1 = new HttpConnectionFactory(httpConfig);
ConnectionFactory h2c = new HTTP2CServerConnectionFactory(httpConfig);
ServerConnector serverConnector = new ServerConnector(server, h1, h2c);
serverConnector.setPort(8080);
server.setConnectors(new ServerConnector[] { serverConnector });
server.start();
server.join();
}
}
The Jetty log line shows that you have configured the server connector to have HTTP/1.1 to be the default protocol (that is the upper-case "HTTP/1.1" before the brackets containing the list of protocols supported).
You don't show your server-side code, but you have two choices:
Configure explicitly the default protocol for the server connector:
serverConnector.setDefaultProtocol("h2c");
Pass the ConnectionFactory objects in the right order to the server connector, since the first one will be the default protocol:
HttpConfiguration httpConfig = new HttpConfiguration();
ConnectionFactory h1 = new HttpConnectionFactory(httpConfig);
ConnectionFactory h2c = new HTTP2CServerConnectionFactory(httpConfig);
ServerConnector serverConnector = new ServerConnector(server, h2c, h1);

Ignore SSL certificate verfication while connecting to elasticsearch from SPRING BOOT via high level rest client

Is there a way to ignore SSL certificate verification while connecting elasticsearch 7.4 using high level rest client. I explored a couple of options but nothing worked in my case. I have a HTTPS ES cluster which I want to connect from my spring boot application by ignoring ssl certificate verification.
hope this will help you, I had the same problem and this is how I resolved.
#Bean
public RestHighLevelClient createSimpleElasticClient() throws Exception {
try {
SSLContextBuilder sslBuilder = SSLContexts.custom()
.loadTrustMaterial(null, (x509Certificates, s) -> true);
final SSLContext sslContext = sslBuilder.build();
RestHighLevelClient client = new RestHighLevelClient(RestClient
//port number is given as 443 since its https schema
.builder(new HttpHost(hostNameOrLoadbalancerURL, 443, "https"))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
#Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setSSLContext(sslContext)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
}
})
.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
#Override
public RequestConfig.Builder customizeRequestConfig(
RequestConfig.Builder requestConfigBuilder) {
return requestConfigBuilder.setConnectTimeout(5000)
.setSocketTimeout(120000);
}
}));
System.out.println("elasticsearch client created");
return client;
} catch (Exception e) {
System.out.println(e);
throw new Exception("Could not create an elasticsearch client!!");
}
}

Resources