How to add endpoints in dropwizard like /healthcheck - dropwizard

we can add healthcheck like
environment.healthChecks().register(
CheckpointConstant.CACHE,
new CacheHealthCheck(adminConfiguration.getAppName())
);
but these are all in the '/healthcheck' interface.
how to add endpoints in port 8081, like '/healthcheck';e.g. '/liveness'.

Related

Swagger UI : Failed to Load API Definition

I've deployed a simple Web API in net5 with swagger enabled (using default settings), which means in Startup.cs:
Configure Services method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyCompany.WebApi", Version = "v1" });
});
Configure method:
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyCompany.WebApi v1"));
And i deploy the same application to 2 Local IIS websites, the first as an application of the Default WebSite running on default port 80, as shown below:
And the second as a Separate WebSite node running on port 8085, as shown below:
Then for the second (hosted as a separate WebSite node), all works fine, so i can see my API definition:
But for the first, hosted as an application under the Default Web Site the API documentation can not be loaded:
Even though the swagger.json file is accessible:
So it look's like swagger is searching for the index.html to display the Swagger-UI in the "root" of the WebSite, and in the case of the first option where the application is hosted under the Default WebSite folder it can not find a way to display the swagger UI. Do we need to add something specific in the swagger definition in this case ?
Thx for any responses !
Emmanuel.
Did you tried this:
app.UseSwaggerUI(c => c.SwaggerEndpoint("swagger/v1/swagger.json", "MyCompany.WebApi v1"));
i removed beginning '/' from swagger json path.

How to Pass access token on Spring Cloud Gateway

I'm new on OAuth2 and Spring Cloud Gateway(And WebFlux things).
My team decided to move from Zuul gateway to Spring Cloud Gateway.
And current Spring Cloud version is "Greenwich.SR1"
The problem is spring cloud gateway always response 401.
How to pass access token on Spring Cloud Gateway properly?
Auth server :
#EnableEurekaClient
#EnableAuthorizationServer
#SpringBootApplication
public class AuthServer {...} // jwtAccessTokenConverter bean included
Zuul server is :
#EnableEurekaClient
#EnableZuulProxy
#SpringBootApplication
public class ZuulServer {...}
Zuul server properties :
zuul:
sensitive-headers: Cookie,Set-Cookie
ignored-services: '*'
routes:
auth: /auth/**
Spring Cloud Gateway Server properties :
spring:
cloud:
gateway:
routes:
- id: auth
uri: lb://auth
predicates:
- Method=POST
- Path=/auth/**
filters:
- RemoveRequestHeader= Cookie,Set-Cookie
- StripPrefix=1
Spring Cloud server build.gradle :
plugins {
id 'java'
id "io.freefair.lombok" version "3.2.0"
id "org.springframework.boot" version "2.1.5.RELEASE"
id "io.spring.dependency-management" version "1.0.6.RELEASE"
}
version = '1.0.0-SNAPSHOT'
description = 'edge-service2'
sourceCompatibility = '11'
dependencies {
implementation platform("org.springframework.cloud:spring-cloud-dependencies:$springCloudVersion")
implementation "org.springframework.boot:spring-boot-starter-security"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-eureka-client"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-ribbon"
implementation "org.springframework.cloud:spring-cloud-starter-netflix-hystrix"
implementation('org.springframework.cloud:spring-cloud-starter-gateway')
implementation "org.springframework.cloud:spring-cloud-config-client"
implementation "de.codecentric:spring-boot-admin-starter-client:$springBootAdminVersion"
implementation "net.gpedro.integrations.slack:slack-webhook:1.4.0"
testImplementation "org.springframework.boot:spring-boot-starter-test"
}
springBoot {
buildInfo()
}
bootJar {
archiveName "${project.name}.jar"
}
There is a feature in Spring Cloud Security for relaying the access token to downstream services via Spring Cloud Gateway: https://cloud.spring.io/spring-cloud-static/spring-cloud-security/2.1.3.RELEASE/single/spring-cloud-security.html#_token_relay
Simply use the TokenRelay Filter for your route or default configuration.
However, this forwards just the access token. "The access token is the artifact that allows the client application to access the user's resource"[1], whereas "an ID token is an artifact that proves that the user has been authenticated"[1], and it also contains the user attributes.
It seems that's what you want anyway, but for all the people out there that use OIDC and want to relay the ID Token, here's some more information.
Write a custom GatewayFilterFactory where you:
get the authenticated Principal via exchange.getPrincipal().ofType(OAuth2AuthenticationToken.class)
map it until you get an oAuth2User Objekt
cast it to an OidcUser
now you can do oidcUser.getIdToken.getTokenValue()
put it into a header of your choice and thus you can also forward the ID Token, not only the Access Token.
[1] https://auth0.com/blog/id-token-access-token-what-is-the-difference/

Springfox Swagger UI behind reverse proxy

I have configured a Spring Boot application with Swagger API documentation and configured Swagger UI.
I also run my backend application behind a reverse proxy that maps all requests from host:port/api to backend_host:port/, when running locally on localhost I map localhost:8082/api. In production a similar mapping is applied.
When I open the Swagger UI from localhost:8082/api/swagger-ui.html it shows the following lines below the title:
[ Base URL: localhost:8080 ]
http://localhost:8082/api/v2/api-docs
When I invoke any rest operation swagger always tries to perform it against localhost:8080 which then fails due to the same origin policy.
I am aware of using pathProvider but it only affects the base URL's path part, not the domain and port. So I can only use it to change the base URL to localhost:8080/api but I would need it to change to localhost:8082/api. Is there a way to set the host dynamically to the current host and port that is active in the browser?
.pathProvider (new RelativePathProvider (servletContext) {
#Override
public String getApplicationBasePath() {
return "/api";
}
})
In my case with a spring-boot:2.2.6 application with springdoc-openapi-ui:1.3.0 (that also has embedded the swagger UI), I solved the proxy problem setting the server URL in this way:
#Configuration
public class OpenApiConfig {
#Value("${server}")
private String url;
#Bean
#Profile("prod")
public OpenAPI customConfiguration() {
return new OpenAPI()
.servers(Collections
.singletonList(new Server().url(url))) //real public URL
.components(new Components())
.info(new Info().title("Dummy API Docs")
.description("Dummy REST API documentation"));
}
}
This change is reflected in the contract (https://real-domain.com/api-docs):
And in the Swagger UI (https://real-domain.com/swagger-ui/index.html?configUrl=/api-docs/swagger-config)
I think in your case you need to configure your proxy to set HTTP Header
(which will be forwarded to your target backend)
to "notify" Swagger endpoints to return custom URL in /apidocs endpoint.
Please configure proxy to set header X-Forwarded-Host to value from Host request header
Explanation:
In your browser when you will visit a url eg. https://my.domain.com/api/swagger-ui.html
the proxy should create and forward header X-Forwarded-Host: my.endpoint.com
to your backend localhost:8082/api/swagger-ui.html
-> so the Swagger /apidocs enpoint could take this header into consideration in response JSON.
My own case - in Microsoft IIS:
I needed to configure Microsoft IIS to serve Swagger IU from Apache Tomcat on 8080 port on HTTPS domain,
so I needed to have following configuration:
<serverVariables>
<set name="HTTP_X_FORWARDED_HOST" value=“{HTTP_HOST}” />
<set name="HTTP_X_FORWARDED_PROTO" value="https" />
</serverVariables>
JuanMorenos answer helped me, however, if anyone is using Springboot and annotations with OpenAPI you can define the URL in your main class
#SpringBootApplication
#OpenAPIDefinition(info = #Info(
version = "2.0",
title = "Swagger - My application",
description = "A description of the application"),
servers = #Server(
url = "http://yourhost:yourport",
description = "A description of the Server "
))

Apigility Zend: Get Authentication Service Using Key Name

I have setup database adapter in config and I can get database service in Factory using key name like:
$connectDb = $services->get('connectDb');
and then I have setup authentication adapter with key name: 'connectoauth2'
It is working fine and authenticate my rest api.
The problem is I want to inject this 'connectoauth2' to my UserEducation Service to getIdentity in So I did in Factory as
$connectDb = $services->get('connectDb');
$connectOAuth2 = $services->get('connectoauth2'); // --> service is not found
$service = new \ConnectApp\Service\UserEducation($connectDb, $connectOAuth2);
return new UserEducationResource($service);
ERROR: Unable to resolve service "connectoauth2" to a factory; are you certain you provided it during configuration?
Even authentication is working fine but Still I can't get Service as i did for database.
Please help!
Thanks!
Are you sure that $services is the service manager? If it is another service locator instance (for example a ControllerManager or ViewHelperManager and not the service manager) you will first have to get the service manager from that service locator:
$serviceManager = $services->getServiceLocator();
and then your service from the service manager:
$service = $serviceManager->get('connectoauth2');
Check for an overview of all the other service locators also here
That is just Authentication Adapter not Authentication Service. So if you need to retrieve identity from Authentication, you should using Authentication Service. In Zend Framework, you can call Authentication Service like this
$authentication = $serviceManager->get('authentication');
And retrieve the identity like this.
$authentication->getIdentity()

Spring OAuth redirect_uri not using https

I have a Spring Boot 1.3.0 application with Spring Security OAuth included as a sort of SSO integration.
The problem is that the application is running in a non-SSL environment with a non-standard port behind a load balancer (F5) that forces SSL and the OAuth provider requires all redirect URLs be registered as https, but the Spring OAuth client (auto-configured with #EnableOAuthSso) will only redirect to the OAuth provider with the following URL...
https://[provider_host]/oauth/authorize?client_id=[redact]&redirect_uri=http://[application_host]/login&response_type=code&scope=[redact]&state=IpMYTe
Note that the return redirect_uri is generated as http. Even though the F5 will force it to https on the way back, our OAuth provider will not allow a non-SSL redirect URI. How can I configure this?
With the exception of my Spring Data JPA controllers, this is the entirety of the app...
AppConfig.java
#SpringBootApplication(exclude = { HibernateJpaAutoConfiguration.class })
#EnableJpaRepositories
public class AppConfig extends SpringBootServletInitializer {
public static void main(final String... args) {
SpringApplication.run(AppConfig.class, args);
}
#Autowired
public DataSource dataSource;
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryInfo() {
final LocalContainerEntityManagerFactoryBean fac = new LocalContainerEntityManagerFactoryBean();
fac.setDataSource(dataSource);
fac.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
fac.setPackagesToScan("[redact]");
final Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
props.put("hibernate.show_sql", "true");
props.put("hibernate.format_sql", "true");
fac.setJpaProperties(props);
return fac;
}
#Bean(name = "transactionManager")
public PlatformTransactionManager getTransactionManager() {
final JpaTransactionManager transactMngr = new JpaTransactionManager();
transactMngr.setEntityManagerFactory(getEntityManagerFactoryInfo().getObject());
return transactMngr;
}
}
SecurityConfig.java
#Configuration
#EnableOAuth2Sso
public class SecurityConfig {
}
application.properties
server.port=9916
server.contextPath=
server.use-forward-headers=true
security.oauth2.client.clientId=[redact]
security.oauth2.client.clientSecret=[redact]
security.oauth2.client.scope=[redact]
security.oauth2.client.accessTokenUri=https://[provider_host]/oauth/token
security.oauth2.client.userAuthorizationUri=https://[provider_host]/oauth/authorize
security.oauth2.resource.userInfoUri=https://[provider_host]/oauth/me
security.oauth2.resource.preferTokenInfo=false
logging.level.org.springframework=TRACE
After digging manually through the configuration classes I was able to find and add the following, which did the trick...
security.oauth2.client.pre-established-redirect-uri=https://[application_host]/login
security.oauth2.client.registered-redirect-uri=https://[application_host]/login
security.oauth2.client.use-current-uri=false
I'm not convinced there isn't a better way to solve the problem of forcing a HTTPS redirect URL, but this fix worked for me.
You may need to ensure that your application understands x-forwarded headers from your load balancer.
Putting this in my application.yml fixed my very similar problem with an application behind an AWS ELB:
server:
tomcat:
remote-ip-header: x-forwarded-for
protocol-header: x-forwarded-proto
Edit: This can be simplified with the more generic configuration:
server:
use-forward-headers: true
For Apache Tomcat use RemoteIpValve in server.xml (above AccessLogValve):
<Valve className="org.apache.catalina.valves.RemoteIpValve"
protocolHeader="X-Forwarded-Proto" />
See also: https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html.
My answer is for people using latest spring version, as the answers suggested above didnt work for me. I am using Spring Boot 2.3.5.RELEASE.
I had a the same issue, I am using Azure AD for oauth2 authentication. My application runs behind the reverse proxy and redirect uri formed was taking http rather than https.
After reading the document https://docs.spring.io/spring-security/site/docs/5.2.x/reference/html/oauth2.html#oauth2Client-auth-code-redirect-uri
, I added below line in the application.properties files and it worked for me
spring.security.oauth2.client.registration.azure.redirect-uri=https://{baseHost}{basePort}{basePath}/login/oauth2/code/azure
Since you have mentioned the use of oauth I think this will help someone to understand the flow of operation. This answer only applies if you are using a reverse proxy such as NGINX.
Cause of the problem,
Your spring boot application is running on the server with a address simlar to http://localhost:8080 . That's what all the spring boot app know about its host. You can inspect this behavior if you check the redirect url in facebook(or other oauth client) error page. It will look something like https://graph.facebook.com/v3.0/me?fields=id,first_name,middle_name,last_name,name,email,verified,is_verified,picture.width(250).height(250),link&redirect_url=http%3A%2F%2Flocalhost%2Flogin%2Ffacebook
See the redirect_url is wrong.
So we need to somehow tell the application that it is hosted under this address.
Quick fix
If you are only looking to fix Facebook OAuth ( Or other oAuth provider), Adding following lines to client will fix.
facebook:
client:
preEstablishedRedirectUri: https://yourdomain.com/
useCurrentUri: false
But, this will only fix the issue at hand ( Also not flexible). But if you need a more concrete solution which is portable, you need to solve this at the reverse proxy.
Open your nginx configuration for the app and change it reflecting as follows.
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Will add the user's ip to the request, some apps need this
proxy_set_header X-Forwarded-Proto $scheme; # will forward the protocole i.e. http, https
proxy_set_header X-Forwarded-Port $server_port; # Will forward the port
proxy_set_header Host $host; # !Important will forward the host address
proxy_pass http://localhost:8080/;
}
Okay so now, nginx is sending the information which were previously hidden to the spring boot app. But yet, spring app is not using this information. To tell it to use these information add the following line to the application.yml.
server.use-forward-headers = true
If you have your reverse proxy in a different node of the same network, you may want to configure the ip of the reverse proxy server with the following. ( replace with your IP)
server.tomcat.internal-proxies=192\.65\.210\.55
I had the same problem.
I add theses two parameters to force HTTPS in redirect_uri :
preEstablishedRedirectUri: https://...
useCurrentUri: false
It works : "redirect_uri" is now using HTTPS
you may need to use spring.oauth2.client.access-token-uri
configuration parameter changed after 1.3.0.M1
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.3.0-M1-Configuration-Changelog

Resources