Kubernetes auth does not work when using non default auth path - spring-vault

I am using spring vault to access Vault from Spring boot app running in Kubernetes.
Version
<dependency>
<groupId>org.springframework.vault</groupId>
<artifactId>spring-vault-core</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
Config
vault:
uri: https://xxx.xxx.com:8200
authentication: KUBERNETES
kubernetes:
role: abc
kubernetes-path: path/to/k8s
service_account_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
Error
o.s.v.a.VaultLoginException: Cannot login using Kubernetes: invalid role name \"abc\";
When I try to login using curl with the same role and token, its success:
VAULT_LOGIN="{\"role\":\"$SA_ROLE\", \"jwt\":\"$SA_JWT_TOKEN\"}"
curl --request POST --data "$VAULT_LOGIN" https://xxx.xxx.com:8200/v1/auth/path/to/k8s/login

It is a bug in spring vault. It does not support custom auth backend path. Pleae find the issue here: https://github.com/spring-projects/spring-vault/issues/462
As a workaround we can fix this by overriding kubeAuthentication method.
#Override
protected ClientAuthentication kubeAuthentication() {
String role = getEnvironment().getProperty("vault.kubernetes.role");
Assert.hasText(role, "Vault Kubernetes authentication: role must not be empty");
String tokenFile = getEnvironment().getProperty("vault.kubernetes.service-account-token-file");
if (!StringUtils.hasText(tokenFile)) {
tokenFile = KubernetesServiceAccountTokenFile.DEFAULT_KUBERNETES_SERVICE_ACCOUNT_TOKEN_FILE;
}
KubernetesJwtSupplier jwtSupplier = new KubernetesServiceAccountTokenFile(
tokenFile);
String path = getEnvironment().getProperty("vault.kubernetes.kubernetes-path");
KubernetesAuthenticationOptions authenticationOptions = KubernetesAuthenticationOptions
.builder() //
.role(role) //
.path(path)
.jwtSupplier(jwtSupplier) //
.build();
return new KubernetesAuthentication(authenticationOptions, restOperations());
}

Related

Spring data redis ignoring user credentials

I am trying to create a redis client with spring data redis with lettuce. What I am observing right is that whatever any password other than default user password doesn't work. Below is the code:-
#Bean
public LettuceConnectionFactory lettuceConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
redisStandaloneConfiguration.setUsername(username);
redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
LettuceConnectionFactory lcf = new LettuceConnectionFactory(redisStandaloneConfiguration);
lcf.setShareNativeConnection(false);
lcf.afterPropertiesSet();
return lcf;
}
#Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(lettuceConnectionFactory());
template.afterPropertiesSet();
return template;
}
In the debug logs, I can see that it is using the username provided:
Trying to get a Redis connection for: redis://test:*******#serverA.net:12345
However, no password other than default user password works. I am able to connect with same credentials on Redis CLI. Eventually gets WRONGPASS invalid username-password pair
What is wrong with above code? Using spring boot vs 2.4.2 & lettuce-core vs 6.0.2
I had spring and lettuce redisearch dependencies in the pom file. Removing them resolved the issue.
<dependency>
<groupId>com.redislabs</groupId>
<artifactId>lettusearch</artifactId>
<version>2.4.4</version>
</dependency>

Authenticate with Azure AD using ASPNET Core 2 from behind Corporate Proxy

I have an ASPNET Core 2 application which I am trying to Authenticate with Azure AD using OpenId. I just have boilerplate code from selecting Single Organization Authentication in the ASPNET Core 2 templates, so no custom code. I followed the article here.
The app is not able to get metadata from the Azure AD application because of proxy. The same URL returns data if I just paste it in browser.
The error I get is:
HttpRequestException: Response status code does not indicate success: 407 (Proxy Authentication Required).
System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
IOException: IDX10804: Unable to retrieve document from: 'https://login.microsoftonline.com/my-tenant-id/.well-known/openid-configuration'.
Microsoft.IdentityModel.Protocols.HttpDocumentRetriever+d__8.MoveNext()
I have another ASPNET 4.5.2 application where I am able to perform authentication with the same Azure AD app as above after setting proxy in code like below:
System.Net.HttpWebRequest.DefaultWebProxy = new WebProxy
{
Address = new Uri("http://my-company-proxy:8080"),
Credentials = new NetworkCredential
{
UserName = "proxyusername",
Password = "proxypassword"
}
};
So Essentially my problem is to get past the Proxy Authentication in ASPNET Core 2.
I have tried Microsoft.AspNetCore.Proxy package. Its pretty much broken and doesn't work for me. Also I tried adding the Proxy entries in machine.config (which are actually not required for 4.5.2 app) but that doesn't work as well. I believe getting past a corporate proxy should be very trivial, but doesn't look like it so far.
Tratcher's comment pointed me in the right direction and I got it working, but just to help everyone with it, below is what you need to do:
builder.AddOpenIdConnect(options => options.BackchannelHttpHandler = new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Credentials = new NetworkCredential
{
UserName = "myusername",
Password = "mypassword"
},
Address = new Uri("http://url:port")
}
});
In Full .net framework setting up a proxy is using a config setting
entry but to use an HTTP proxy in .net core ,you have to implement
IWebProxy interface.
Microsoft.AspNetCore.Proxy is proxy middleware which serves a different purpose (to setup reverse proxy) not as an http proxy .Refer this article for more details
To implement a webproxy in .net core,
public class MyHttpProxy : IWebProxy
{
public MyHttpProxy()
{
//here you can load it from your custom config settings
this.ProxyUri = new Uri(proxyUri);
}
public Uri ProxyUri { get; set; }
public ICredentials Credentials { get; set; }
public Uri GetProxy(Uri destination)
{
return this.ProxyUri;
}
public bool IsBypassed(Uri host)
{
//you can proxy all requests or implement bypass urls based on config settings
return false;
}
}
var config = new HttpClientHandler
{
UseProxy = true,
Proxy = new MyHttpProxy()
};
//then you can simply pass the config to HttpClient
var http = new HttpClient(config)
checkout https://msdn.microsoft.com/en-us/library/system.net.iwebproxy(v=vs.100).aspx

BigQuery Authentication Problems

I'm starter with BigQuery.
And my Problem comes with Authentication.
The credential File has been created and store at:
/home/ltloi/.config/gcloud/application_default_credentials.json
Content:
{
"type": "service_account",
"project_id": "xxx",
"private_key_id": "xxx",
"private_key": "-----BEGIN PRIVATE KEY-----xxx\n-----END PRIVATE KEY-----\n",
"client_email": "xxx",
"client_id": "xxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/bigqueryservices1%40neon-deployment-141106.iam.gserviceaccount.com"
}
Sourcecode:
// just authentication with google big query
public static Bigquery createAuthorizedClient() throws IOException {
// Create the credential
HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
// Depending on the environment that provides the default credentials (e.g. Compute Engine, App
// Engine), the credentials may require us to specify the scopes we need explicitly.
// Check for this case, and inject the Bigquery scope if required.
if (credential.createScopedRequired()) {
credential = credential.createScoped(BigqueryScopes.all());
}
return new Bigquery.Builder(transport, jsonFactory, credential)
.setApplicationName("Bigquery Samples")
.build();
}
The Problems Issue:
Exception in thread "main" java.io.IOException: Error reading credential file from location
/home/ltloi/.config/gcloud/application_default_credentials.json
Error:
java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getCredentialUsingWellKnownFile(DefaultCredentialProvider.java:251)
at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredentialUnsynchronized(DefaultCredentialProvider.java:117)
at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:91)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:213)
at com.google.cloud.bigquery.samples.GettingStarted.createAuthorizedClient(GettingStarted.java:53)
at com.google.cloud.bigquery.samples.GettingStarted.main(GettingStarted.java:135)
When I try debug and the code shows that comes with SSL Issue form HttpClient.
Experts please help resolve it. I have try to add SSL of
https://accounts.google.com/o/oauth2/auth
https://www.googleapis.com/oauth2/v1/certs
But Can NOT resolve.
I also install Cloud SDK and But the also CAN NOT resolve.
{
"client_id": "XXXX",
"client_secret": "XXX",
"refresh_token": "XXXX",
"type": "authorized_user"
}
Note: I have Done gcloud beta auth application-default login gcloud beta auth application-default print-access-token
Thanks & Regards,
Were the application default credentials created using the following command?
gcloud beta auth application-default login
I think there are two additional quick tests that you could do to get closer to the problem source. First, you can try this to verify that your credentials are fine:
gcloud beta auth application-default print-access-token
Then, you could copy and paste this brief python script to verify that it works (from here: https://cloud.google.com/bigquery/authentication)
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get_application_default()
# Construct the service object for interacting with the BigQuery API.
bigquery_service = build('bigquery', 'v2', credentials=credentials)

Servicestack Authentication IsAuthenticated always false

Hi am trying to use OAuth authentication provided by servicestack
plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
new BasicAuthProvider(), new LinkedInOAuth2Provider(new AppSettings()),
new GoogleOAuth2Provider(new AppSettings()) }));
//Use Redis Repo
var userRepository = new RedisAuthRepository(redisClientsManager);
container.Register<IUserAuthRepository>(userRepository);
//Register Users with redis
Plugins.Add(new RegistrationFeature());
After Successful authentication by Google/LinkedIn the redis AuthRepo contains this, We can see that isAuthenticated is False even after Successful authentication.
Could anyone let me know more about OAuth, Because there are many Secrets of it when comes to Mobile.
Eg: What Redirect Uri should i give in LinkedIn Console..! if i use OAuth for Mobiles ..? And how can i refresh session on each App StartUp.
Your screenshot does not show an authenticated User Session, which would have IsAuthenticated = true and include OAuth details returned by each OAuth provider in ProviderOAuthAccess collection.
ServiceStack OAuth Live Demos
See the httpbenchmarks.servicestack.net for an example of a working Live Demo that uses Google and LinkedIn OAuth2. The HttpBenchmarks Github Repo includes a step-by-step Guide explaining how to Configure OAuth in ServiceStack, including an example of a App Settings configuration and how to configure Glimpse for inspecting DotNetOpenAuth errors.
The mvc.servicestack.net Live Demo is another example that contains a working configuration using a number of Auth Providers.
Use AppHost AppSettings
When registering the OAuth Provider you should use the AppHost's AppSettings instead of injecting a new AppSettings() that way all Auth Providers will use the same configured AppSettings for your AppHost, e.g:
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
new BasicAuthProvider(),
new LinkedInOAuth2Provider(base.AppSettings),
new GoogleOAuth2Provider(base.AppSettings)
}));

How do you configure grails to resolve dependencies from a password protected repository?

I have a password protected internal maven repository I'd like to use to resolve dependencies in grails.
Does anyone know how to configure grails to use authentication when accessing a repository?
I'm running grails 1.2.1.
You can look in the docs: 3.7.2) Dependency Repositories -> Authentication
From the Docs:
If your repository requires some form of authentication you can specify as such using a credentials block:
credentials {
realm = ".."
host = "localhost"
username = "myuser"
password = "mypass"
}
Just making Brandon answer a bit more specific for the Nexus and Artifactory Maven repositories, as the realm attribute is key for this to work.
If you are using Nexus the credentials block look like this:
credentials {
realm = "Sonatype Nexus Repository Manager"
host = "hostname"
username = "username"
password = "password"
}
, but if you are using Artifactory, it should look like this:
credentials {
realm = "Artifactory Realm"
host = "hostname"
username = "username"
password = "password"
}
You need to add this block to your BuildConfig.groovy file, but if your code is going to be open sourced or you want this setting for all your projects, you can add the block inside your ~/.grails/settings.groovylike this:
grails.project.ivy.authentication = {
credentials {
realm = "your realm"
host = "hostname"
username = "username"
password = "password"
}
}
Cheers,
Angel.