I have configured my goclient with keycloak.I am reading the keycloak server details from keycloak.json file which is present inside my Go client.
My whole setup is in Kubernetes cluster.Everytime when new keycloak server comes up how should I pass keycloak.json file to the Go client so that it can read the details from json file?
Is there a way I can get the keycloak.json file with all the client configuration details without having to login to keycloak and download it ?
"realm": "SolutionAdmin",
"auth-server-url": "localhost:8081/auth",
"ssl-required": "none",
"resource": "admin",
"credentials": {
"secret": "6ee0f523-c392-4406-bb14-ba315125c6ea"
},
"confidential-port": 0
}
if you want to have a pre-configured embedded keycloak server, you'll need to extend KeycloakApplication and have it configured to trigger in lieu of the base class. in this example, KeycloakProperties is just a representation of all the keycloak properties we used in application.properties. but you can get the gist of it. fair warning: i did not write this, but am figuring out how a coworker did for another project.
public class EmbeddedKeycloakApplication extends KeycloakApplication {
public final KeycloakProperties keycloakProperties;
public EmbeddedKeycloakApplication() {
super();
keycloakProperties = SpringContextAdapter.getBean(KeycloakProperties.class);
System.getProperties().putAll(keycloakProperties.getRealmProperties());
createMasterRealmAdminUser();
createRealm();
}
private void createMasterRealmAdminUser() {
log.debug("Creating administrative user.");
String username = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_USERNAME);
String password = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_PASSWORD);
String email = keycloakProperties.getServer(KeycloakProperties.ADMIN_USER_EMAIL);
KeycloakSession session = getSessionFactory().create();
ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
try {
session.getTransactionManager().begin();
if (!applianceBootstrap.isNoMasterUser()) {
log.debug("Administrative user already exists. No work to do.");
return;
}
applianceBootstrap.createMasterRealmUser(username, password);
RealmModel adminRealm = session.realms().getRealm(Config.getAdminRealm());
UserModel adminUser = session.users().getUserByUsername(username, adminRealm);
adminUser.setEmail(email);
adminUser.setEmailVerified(true);
session.getTransactionManager().commit();
log.info("Created administrative user {}", username);
} catch (Exception ex) {
log.error("Couldn't create keycloak master admin user: {}", ex.getMessage());
session.getTransactionManager().rollback();
}
session.close();
}
private void createRealm() {
String realmImportFilename = keycloakProperties.getRealmImportFile();
KeycloakSession session = getSessionFactory().create();
String realmId = keycloakProperties.getRealm(KeycloakProperties.REALM_ID);
try {
session.getTransactionManager().begin();
RealmManager manager = new RealmManager(session);
if (manager.getRealm(realmId) != null) {
log.debug("{} realm already exists. No work to do.", realmId);
return;
}
Resource realmImportFile = new ClassPathResource(realmImportFilename);
RealmRepresentation rep =
JsonSerialization.readValue(
realmImportFile.getInputStream(), RealmRepresentation.class, true);
manager.importRealm(rep);
log.info("Imported Realm json file {}", realmImportFilename);
session.getTransactionManager().commit();
} catch (Exception e) {
log.error("Failed to import Realm json file {}: {}", realmImportFilename, e.getMessage(), e);
session.getTransactionManager().rollback();
}
session.close();
}
}
#Configuration
public class EmbeddedKeycloakConfig {
#Bean
ServletRegistrationBean<HttpServlet30Dispatcher> keycloakJaxRsApplication(
KeycloakProperties keycloakProperties, DataSource dataSource) throws NamingException {
mockJndiEnvironment(dataSource);
var contextPath = keycloakProperties.getServer(KeycloakProperties.SERVER_CONTEXT_PATH);
ServletRegistrationBean<HttpServlet30Dispatcher> servlet =
new ServletRegistrationBean<>(new HttpServlet30Dispatcher());
servlet.addInitParameter(
"javax.ws.rs.Application", EmbeddedKeycloakApplication.class.getName());
servlet.addInitParameter(
ResteasyContextParameters.RESTEASY_SERVLET_MAPPING_PREFIX, contextPath);
servlet.addInitParameter(ResteasyContextParameters.RESTEASY_USE_CONTAINER_FORM_PARAMS, "true");
servlet.addInitParameter(ResteasyContextParameters.RESTEASY_DISABLE_HTML_SANITIZER, "true");
servlet.addUrlMappings(contextPath + "/*");
servlet.setLoadOnStartup(1);
servlet.setAsyncSupported(true);
return servlet;
}
#Bean
FilterRegistrationBean<EmbeddedKeycloakRequestFilter> keycloakSessionManagement(
KeycloakProperties keycloakProperties) {
FilterRegistrationBean<EmbeddedKeycloakRequestFilter> filter = new FilterRegistrationBean<>();
filter.setName("Keycloak Session Management");
filter.setFilter(new EmbeddedKeycloakRequestFilter());
filter.addUrlPatterns(
keycloakProperties.getServer(KeycloakProperties.SERVER_CONTEXT_PATH) + "/*");
return filter;
}
private void mockJndiEnvironment(DataSource dataSource) throws NamingException {
NamingManager.setInitialContextFactoryBuilder(
env ->
environment ->
new InitialContext() {
#Override
public Object lookup(Name name) {
return lookup(name.toString());
}
#Override
public Object lookup(String name) {
if ("spring/datasource".equals(name)) {
return dataSource;
}
return null;
}
#Override
public NameParser getNameParser(String name) {
return CompositeName::new;
}
#Override
public void close() {
// NOOP
}
});
}
}
Related
I need to test this method.
public String getTenantName(String tenantId) {
var tenant = getTenant(tenantId);
if (tenant == null) {
throw new TenantNotFoundException(tenantId);
}
return tenant.getTenantname();
}
but I am having problems with mocking the below loading cache
LoadingCache<String, Tenant> tenantCache = CacheBuilder.newBuilder().maximumSize(1000)
.expireAfterAccess(24, TimeUnit.HOURS).build(new CacheLoader<String, Tenant>() {
#Override
public Tenant load(String tenantId) {
return tenantClient.getTenant(tenantId);
}
});
as this is being called by another private method
private Tenant getTenant(String tenantId) {
try {
if (StringUtils.isBlank(tenantId)) {
return null;
}
return tenantCache.get(tenantId);
} catch (TenantNotFoundException | ExecutionException e) {
logger.error(tenantId, e);
throw new TenantNotFoundException(tenantId);
}
}
I would really appreciate some help here.
I mocked loading cache
#mock
LoadingCache<String, Tenant> tenantCache;
and then in my test function I create a tenant object and return that on tenantCache.get() call.
tenantCache = CacheBuilder.newBuilder().maximumSize(1000)
.expireAfterAccess(24, TimeUnit.HOURS).build(new CacheLoader<String, Tenant>() {
#Override
public Tenant load(String tenantId) {
return tenantClient.getTenant(tenantId);
}
});
Map<String, Tenant> map = new HashMap<String, Tenant>();
map.put("test", tenant);
tenantCache.putAll(map);
also for tenantClient I changed that to return tenant.
return tenantClient.getTenant(id) =>> return tenant;
as tenantClient is calling another API.
So, LoadingCache appears as a variable inside the service but it is implemented as an anonymous class. Therefore we need to mock LoadingCache and use
when(tenantCache.get(anyString())).thenReturn(new Tenant());
I want to load the values from json file upon the Spring Boot Application is started.
My code for the Configuration File is like the below:
#Configuration
#Getter
public class FedexAPIConfig {
private final static String JSON_FILE = "/static/config/fedex-api-credentials.json";
private final boolean IS_PRODUCTION = false;
private FedexAPICred apiCredentials;
public FedexAPIConfig() {
try (InputStream in = getClass().getResourceAsStream(JSON_FILE);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
JSONObject json = new JSONObject();
// this.apiCredentials = new JSONObject(new JSONTokener(reader));
if (IS_PRODUCTION) {
json = new JSONObject(new JSONTokener(reader)).getJSONObject("production");
} else {
json = new JSONObject(new JSONTokener(reader)).getJSONObject("test");
}
System.out.println(json.toString());
this.apiCredentials = FedexAPICred.builder()
.url(json.optString("url"))
.apiKey(json.optString("api_key"))
.secretKey(json.optString("secret_key"))
.build();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and with this, when the application is in progress of startup, values are successfully printed on the console.Startup console log
When I tried to call this value from other ordinary class, like the below:, it brings nothing but just throws NullPointerException... What are my faults and what shall I do?
public class FedexOAuthTokenManager extends OAuthToken {
private static final String VALIDATE_TOKEN_URL = "/oauth/token";
private static final String GRANT_TYPE_CLIENT = "client_credentials";
private static final String GRANT_TYPE_CSP = "csp_credentials";
#Autowired
private FedexAPIConfig fedexApiConfig;
#Autowired
private Token token;
#Override
public void validateToken() {
// This is the part where "fedexApiConfig" is null.
FedexAPICred fedexApiCred = fedexApiConfig.getApiCredentials();
Response response = null;
try {
RequestBody body = new FormBody.Builder()
.add("grant_type", GRANT_TYPE_CLIENT)
.add("client_id", fedexApiCred.getApiKey())
.add("client_secret", fedexApiCred.getSecretKey())
.build();
response = new HttpClient().post(fedexApiCred.getUrl() + VALIDATE_TOKEN_URL, body);
if (response.code() == 200) {
JSONObject json = new JSONObject(response.body().string());
token.setAccessToken(json.optString("access_token"));
token.setTokenType(json.optString("token_type"));
token.setExpiredIn(json.optInt("expires_in"));
token.setExpiredDateTime(LocalDateTime.now().plusSeconds(json.optInt("expires_in")));
token.setScope(json.optString("scope"));
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
fedexApiConfg is null even though I autowired it in prior to call.
And this FedexOAuthTokenManager is called from other #Component class by new FedexOAuthTokenManager()
Did you try like below?
Step 1: Create one Configuration class like below
public class DemoConfig implements ApplicationListener<ApplicationPreparedEvent> {
#Override
public void onApplicationEvent(ApplicationPreparedEvent event) {
//Load the values from the JSON file and populate the application
//properties dynamically
ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
Properties props = new Properties();
props.put("spring.datasource.url", "<my value>");
//Add more properties
environment.getPropertySources().addFirst(new PropertiesPropertySource("myProps", props));
}
To listen to a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent().The ApplicationPreparedEvent is invoked very early in the lifecycle of the application
Step 2: Customize in src/main/resources/META-INF/spring.factories
org.springframework.context.ApplicationListener=com.example.demo.DemoConfig
Step 3: #Value in spring boot is commonly used to inject the configuration values into the spring boot application. Access the properties as per your wish.
#Value("${spring.datasource.url}")
private String valueFromJSon;
Try this sample first in your local machine and then modify your changes accordingly.
Refer - https://www.baeldung.com/spring-value-annotation
Refer - https://www.knowledgefactory.net/2021/02/aws-secret-manager-service-as.html
I wanna create an application to send emails to several recipients. It feeds email addresses from a csv file and sends an email to each recipient, and I'm getting some trouble doing this.
Could you help me please?
Here is my CSVHelper.java
#Component
public class CSVHelper
{
public static String TYPE = "text/csv";
static String[] HEADERs = { "id", "email", "dateEcheance"};
//This method is used to filter the csv file and get only the emails
public List<ContactsFile> csvToEmails() throws NumberFormatException, ParseException
{
InputStream is = null;
try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());)
{
List<ContactsFile> emailsList = new ArrayList<>();
Iterable<CSVRecord> csvRecords = csvParser.getRecords();
for (CSVRecord csvRecord : csvRecords)
{
ContactsFile contact = new ContactsFile(csvRecord.get("email"));
emailsList.add(contact);
}
System.out.println(emailsList);
return emailsList;
}
catch (IOException e) { throw new RuntimeException("fail to get emails: " + e.getMessage()); }
}
We call csvToEmails() method in the controller to send the emails
#Autowired
private CSVHelper csvHelper;
#PostMapping("/getdetails")
public #ResponseBody EmailNotification sendMail(#RequestBody EmailNotification details) throws Exception {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
try {
helper.setTo((InternetAddress) csvHelper.csvToEmails());
helper.setText(details.getMessage(),true);
helper.setSubject("Test Mail");
} catch (javax.mail.MessagingException e) {
e.printStackTrace();
}
sender.send(message);
return details;
this is an example of the csv file:
id,email,dateEcheance
1,address#email.com,10/05/2021
2,address2#email.com,10/02/2021
I'm new to spring boot, and I'm in trouble completing this project.
Assuming that you've mail server configurations in place. First, you need to provide the JavaMailSender implementation. Spring does provide the implementation for the same. You've to create a bean and config the mail server configurations as follows.
#Configuration
public class MailConfig {
#Autowired
private Environment env;
#Bean
public JavaMailSender mailSender() {
try {
JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
mailSenderImpl.setHost(env.getRequiredProperty("mail.smtp.host"));
mailSenderImpl.setUsername(env.getRequiredProperty("mail.smtp.username"));
mailSenderImpl.setPassword(env.getRequiredProperty("mail.smtp.password"));
mailSenderImpl.setDefaultEncoding(env.getRequiredProperty("mail.smtp.encoding"));
mailSenderImpl.setPort(Integer.parseInt(env.getRequiredProperty("mail.smtp.port")));
mailSenderImpl.setProtocol(env.getRequiredProperty("mail.transport.protocol"));
Properties p = new Properties();
p.setProperty("mail.smtp.starttls.enable", "true");
p.setProperty("mail.smtp.auth", "true");
mailSenderImpl.setJavaMailProperties(p);
return mailSenderImpl;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Configuration settings in application.properties. Add settings according to the mail server.
# SMTP mail settings
mail.smtp.host=**********
mail.smtp.username=**********
mail.smtp.password=**********
mail.smtp.port=**********
mail.smtp.socketFactory.port=**********
mail.smtp.encoding=utf-8
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.timeout=10000
mail.smtp.starttls.enable=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
CSVHelper.java
#Component
public class CSVHelper {
// This method is used to filter the csv file and get only the emails
public List<String> csvToEmails() {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("csvFile.csv");
try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
CSVParser csvParser = new CSVParser(fileReader,
CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());) {
List<String> emails = new ArrayList<>();
Iterable<CSVRecord> csvRecords = csvParser.getRecords();
for (CSVRecord csvRecord : csvRecords) {
String email = csvRecord.get("email");
emails.add(email);
}
return emails;
} catch (IOException e) {
throw new RuntimeException("fail to get emails: " + e.getMessage());
}
}
}
Send mail service
#Service
public class MailSenderService {
#Autowired
private CSVHelper csvHelper;
#Autowired
private JavaMailSender sender;
public void sendMail(EmailNotification details) {
try {
List<String> recipients = csvHelper.csvToEmails();
String[] to = recipients.stream().toArray(String[]::new);
JavaMailSenderImpl jms = (JavaMailSenderImpl) sender;
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// add the sender email address below
helper.setFrom("sender#mail.com");
helper.setTo(to);
helper.setText(details.getMessage(), true);
helper.setSubject("Test Mail");
sender.send(message);
} catch (javax.mail.MessagingException | NumberFormatException e) {
// action for exception case
}
}
}
this question is asked very often, but all the answers 2 or 3 years old. I have a login for my Android app and the date is saved in a MySQL database on my cloud server which has a SSL certificate.
When I test my app on my local machine everything is fine, but when I try to connect with my cloud server I get the message "Trust Anchor for Certification path not found". My credentials are ok.
I know that I have to set a sslSocketFactory. I tried so many, but one worked. I´m sitting now for days. May someone had a idea how to solve
here my code without sslSocketFactory
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.logintest, container, false);
btn_login = view.findViewById(R.id.btn_logintest);
email = view.findViewById(R.id.etEmail);
password = view.findViewById(R.id.etPassword);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
public void login() {
str_email = email.getText().toString();
str_password = password.getText().toString();
if(!str_email.equals("") && !str_password.equals("")) {
StringRequest request = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction= fragmentManager.beginTransaction();
DummyFragment dummyFragment = new DummyFragment();
fragmentTransaction.replace(R.id.container,dummyFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Log.e("Text: ", response);
Toast.makeText(getActivity(), "erfolgreicher Text: " +response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Text: " +error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("str_email", email.getText().toString());
params.put("str_password", password.getText().toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
try {
HashMap<String, String> headers = new HashMap<>();
String credentials = "xxxxxxxxx:xxxxxxxxxx";
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
return headers;
} catch (Exception e) {
Log.e(TAG, "Authentication failure");
Toast.makeText(getActivity(), "" +e, Toast.LENGTH_LONG).show();
}
return super.getHeaders();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(request);
}
else {
if (email.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Bitte Email Adresse eingeben", Toast.LENGTH_SHORT).show();
} else if (password.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Bitte Passwort eingeben", Toast.LENGTH_SHORT).show();
}
}
}
});
return view;
}
}
I tried the code from android developer page, but some error. I tried to set network_security.xml but it didn't worked for me. When I test my credentials with postman I get response 200.
I want to upload file on remote server, currently i am only able to upload on local machine. below is my code
#PostMapping("/upload")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
return new UploadFileResponse(fileName, fileDownloadUri,file.getContentType(), file.getSize());
}
file.upload-dir=C:\\Test
Thanks in Advance!
EDIT:
1. Use case : You want to upload the file locally (i.e. where your application is running):
You create StorageService interface and an implementing class FileSystemStorageService:
#Service
public class FileSystemStorageService implements StorageService {
private final Path rootLocation;
#Autowired
public FileSystemStorageService(StorageProperties properties) {
this.rootLocation = Paths.get(properties.getLocation());
}
#Override
public void store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + filename);
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, this.rootLocation.resolve(filename),
StandardCopyOption.REPLACE_EXISTING);
}
}
catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
}
And the controller class:
#Controller
public class FileUploadController {
private final StorageService storageService;
#Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
#PostMapping("/")
public String handleFileUpload(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
You can find the whole sample under https://github.com/spring-guides/gs-uploading-files.
2. Use case : You want to upload the file to a remote server:
I recommend in this case to use SFTP.
You create a RemoteFileSystemStorageService implementing the StorageService (Already created in the first use case).
#Service
public class RemoteFileSystemStorageService implements StorageService {
#Autowired
private StorageProperties properties
final private ChannelSftp channelSftp;
#PostConstruct
public void setUpSsh(){
JSch jsch = new JSch();
Session jschSession = jsch.getSession(properties.getUsername(),
properties.getRemoteHost());
jschSession.setPassword(properties.getPassword());
jschSession.connect();
this.channelSftp = (ChannelSftp)jschSession.openChannel("sftp");
}
#Override
public void store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + filename);
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream()) {
this.channelSftp.connect();
this.channelSftp.put(inputStream, properties.getRemoteServerDirectory());
}
}
catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
finally{
this.channelSftp.close();
}
}