Getting kubernetes secret / env for authentication into java application

2/20/2019

I hava a java spring.boot application that uses Kubernetes, I'we configured this .yaml file

- name: ACTUATOR_USERNAME
  valueFrom:
    secretKeyRef:
      name: actuator
      key: username
- name: ACTUATOR_PASSWORD
  valueFrom:
    secretKeyRef:
      name: actuator
      key: password

added this attributes to my application.propertis

security.user.name=${ACTUATOR_USERNAME}
security.user.password=${ACTUATOR_PASSWORD}

secret is created at server side, how do I retrieve this values inside my class

package com.greenqloud.usage.healthcheck;

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests()
                .anyRequest().hasRole("USER")
                .and()
                .httpBasic();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("actuator username: " + System.getenv("ACTUATOR_USERNAME"));
        System.out.println("actuator password: " + System.getenv("ACTUATOR_PASSWORD"));

        auth.inMemoryAuthentication()
                .withUser("actuator").password("{noop}actuator123").roles("USER");
    }
}

the only way I have found is to use the System.out.getenv("ACTUATOR_USERNAME") but I'm sure there is a better way to achieve this?

-- JonB
java
kubernetes
spring-boot-actuator

2 Answers

2/20/2019

I am agree with @Kuikiker about getenv(). But one question why do u want to store credential in env variable. Unless u have some special need I believe you will be better off store them in your application.properties with encrypted value. I usually use jasypt encipher for that (https://www.baeldung.com/spring-boot-jasypt). Hope this helps.

-- Reedwanul Islam
Source: StackOverflow

2/20/2019

System.getenv() is used to retrieve environment variable values; there is nothing wrong with it. However, since you are using SpringBoot you may find the following question valuable: Read environment variable in SpringBoot

-- Kuikiker
Source: StackOverflow