Add new app_config value in Backstage and use it in frontend - app-config

I have added new app_config key value, but can't access it in frontend. When I console log the the config data I see the new key in filtered_keys, but not able to access it with config.getString("").

Related

How can I open a link in react web app without giving user name and password again?

I have a running react web application with protected routes. We are using JSON web tokens. We also using Redux saga. I want to provide a link and This need to be open in a new tab. But when the user logged in and click on the link, the link opens in a new tab but it asks user name and password again. I want to share the current state with the app in the new tab.
How are you storing the JWT? The most common way to do it is to store the JWT in cookies which automatically get sent on every request in the same domain. As long as the JWT is in a cookie, the cookie gets passed to the server, and the server checks for and uses the JWT payload, you should be able to open a new tab just fine.

Problem in create, update and delete Cookie using react-cookie

I am creating a cookie by using react babel but I am facing a problem. When I create a cookie the cookie created in the browser but when I click on the URL to authenticate then the cookies remove from the browser, and when I create it again, the two cookies with an old one and a new one is created in the browser.
When I delete a cookie and refresh the page the two cookies again created in the browser. I don't understand how is this possible?
I am using this code to create and delete a cookie-
cookies.remove("WebTimeClock", {
path: "/labor-settings",
domain: "localhost",
});
and for create a cookie I am using this-
cookies.set("WebTimeClock", currentUniqueID, {
expires: new Date(dateTime),
});
I am using "react-cookie" for this.
You can set multiple cookies of the same name if you set them against different paths. In your first example, you define the path, but in the second, you do not. Not setting a path will use the existing URL path. If I do this on stack overflow, you can see from dev tools there are now two cookies:

How do I hide an API key in Create React App?

I made a weather app in Create React App (create-react-app). How do I hide the API key so that I can commit to GitHub?
Right now, the key is in App.js:
const API_KEY = "123456";
Unfortunately, keeping any key in your React client, even if you are using gitignore and an .env file, is not secure. As pointed out by Claudiu Creanga, React environment variables are embedded in the build and are publicly accessible.
You should really only save API keys or secrets in your backend such as Node.js or Express.js. You can have your client send a request to your backend API, which can then make the actual API call with the API key and send the data back to your client.
Disclaimer
WARNING: Do not store any secrets (such as private API keys) in your
React app!
Environment variables are embedded into the build, meaning anyone can
view them by inspecting your app's files.
The following answer provides a correct way to store non-secret data in environment variables. Remember that secret data is accessible through developer tools, making it unsafe to store as environment variables. If you want to store some secret data then storing in the backend is the better option and if the client wants to access secret data, it can be accessed by making a request to the server. (Refer to Antonia's answer for more details on storing secret data.)
As it turns out, create-react-app has some built-in functionality to help you with that. Thank you George Karametas for this insight. To access that functionality, you need to:
1. Create a file called .env in the root of your project's directory.
- your_project_folder
- node_modules
- public
- src
- .env <-- create it here
- .gitignore
- package-lock.json
- package.json
2. Inside the .env file, prepend REACT_APP_ to your API key name of choice and assign it.
The create-react-app tool uses REACT_APP_ to identify these variables. If you don't start your API key name with it, create-react-app won't see it.
// .env
REACT_APP_API_KEY=your_api_key <-- yes
API_KEY=your_api_key <-- no
// Example (from 이준형's response):
REACT_APP_WEATHER_API_KEY=123456
3. Add the .env file to your .gitignore file.
After you add the line below, save the .gitignore file and do a git status to make sure your .env file does not appear as a new file in git.
// .gitignore
# api keys
.env <-- add this line
# dependencies
/node_modules
...
4. Access the API key via the process.env object.
To check that you can access your API key, go to your App.js file and add a console.log at the top below the require statements. After saving the file and reloading the page, if the console log does not show your API key, try restarting the react server. Be sure to remove the console log line before committing your code.
// src/App.js
import React, { Component } from 'react';
import './App.css';
console.log(process.env.REACT_APP_WEATHER_API_KEY)
class App extends Component {
...
Warning
Unless you're making tutorial applications, don't put secrets such as API keys in client-side source code (e.g., a React app). From Create React App's documentation:
WARNING: Do not store any secrets (such as private API keys) in your
React app!
Environment variables are embedded into the build, meaning anyone can
view them by inspecting your app's files.
First, create an .env file in the root of your project, i.e., where you would run react-scripts start (or yarn start) outside of your source folder.
Then, add
REACT_APP_WEATHER_API_KEY=123456
Before commit, you should exclude this .env file, so find the .gitignore file and add .env.
The name of the variable needs to begin with REACT_APP_ which protects you from accidentally including secrets with your build.
Don't forget to add .env in the .gitignore file.
To use the environment variables in your code:
const API_KEY = process.env.REACT_APP_WEATHER_API_KEY;
In order to read environment variables after having added them to .env, restart your server.
From the React documentation:
WARNING: Do not store any secrets (such as private API keys) in your React app!
Environment variables are embedded into the build, meaning anyone can
view them by inspecting your app's files.
Although the question has already been answered by Antonia Blair, I would like to through some more light on some basic rules.
1: Most of the answers are suggesting to make use of the .env file. I would like to make it clear for once and all that .env is not here to add any security layer. The .env as the name depicts is only here to set up an environment at build time. e.g. by using the environment variables you set some global values at build time and can access these values in your application at runtime.
2: React is simply a framework running your JavaScript code in the client browser. So the client has complete access to the JavaScript (React) code. Nothing is secure on the client-side. So never think of making something secure or hidden from the client by just keeping all your code client-side. Whenever you need to hide something from the client, there is something server-side which you need to incorporate. Only the server-side code is secure from the client-side.
3: So what you do is, you will keep your secure keys on the server-side.
Suppose the purpose of your secure keys is to make a cookie for your client. so the client needs the cookie not the secure keys, right? So the client-side makes a request to the server for a cookie, the server makes the cookie by using the secure keys and returns the cookie to the client. After all the client is only here to eat the cookie and not to know how do we make a cookie right?
4: So the thumb rule is that wherever you have some confidential data, you will keep it on the server. The server will use this confidential data and return the result data to be exposed to the client.
A user has asked for a coding example, so I have put up a real-time scenario which I have handled using the above described technique.
Here is my use case:
I have a React app which submits a public form to non public API.
The non public API is Harvest API hosted by:
https://www.greenhouse.io/
This API requires an authentication header for making requests with it. I have subscribed with the API owner and received a secret token from them which I can use with my requests to get access to their API
Af course, I want to keep my token personal and do not expose it to public users
I have used the Axios client to communicate with the API
I have two ways to perform the above described scenario:
The Incorrect Method
I am making requests to the API directly from my React application
Let’s say below is the API endpoint which I want to hit
apiURL = https://boardsapi.greenhouse.io/v1/boards/xyz/jobs/" + jobId + ""
The above API endpoint requires an authorization header, and I will provide my secret token in it.
const config = {
headers: {
"Authorization": "Basic ####MySecretCode#####",
} };
Suppose I want to post some form data with this request
let formData = MyFormData
I can now send my request using the Axios client like below
let result = await axios.post(apiURL, formData, config);
Using the above technique, I can successfully post my form data to the Harvest API.
But like I said, that it's an incorrect way to communicate with this API. Because I have exposed my secret token on the client side.
The Correct Way
I built an API on Node.js and hosted it publicly.
Suppose I want to post some form data to the Harvest API
let formData = MyFormData
I am not going to hit the Harvest API directly from my client application. And instead I have exposed and endpoint in my middleware API to handle this.
Let’s say the below is the endpoint URL of my middleware API which I want to hit
apiURL = https://proxy-server/apply
The above API endpoint does not requires an authorization header. So I can send a post requests using the Axios client like below:
let result = await axios.post(apiURL, formData);
The difference is clear. I have not supplied the secret token this time in my request. Because this is not a direct request to the Harvest API and instead it's a request to a middle-ware API which is developed and hosted by me.
I receive this request in my middle-ware API, add my secret token with it and forward it to the Harvest API. The response from Harvest API is returned to our middle_ware API and hence forward back to our React client application.
The secret token now resides on my server-side API and safe from external users.
Here's what worked for me:
I created the .env file in the root folder.
Within that folder I added my key:
REACT_APP_API_KEY_YT = "key"
// I added 'YT' for YouTube which is where my API key is from
Then I went to .gitignore. Or create a .gitignore file in your root directory if you don't have it. Within .gitignore, I added .env
# API key
.env
Then I went back to the root of my App js file. For me, that was index.js. For others, it is probably App.js.
There I created a const API_KEY
const API_KEY =`${process.env.REACT_APP_API_KEY_YT}`
I checked if it was working by console logging it.
console.log("API", API_KEY)
I was getting undefined.
I stopped the server (Ctrl + C) and restarted the server.
Afterwards I was able to see the key.
Here is an example of finding the API key in code even when you attempt to hide it in an environment variable.
I built a very simple app using the NewsAPI, which required me to register for an API key. Here is my fetch to the NewsAPI endpoint using the API key as an environment variable.
fetch(`https://newsapi.org/v2/top-headlines?q=${keyword}&apiKey=${process.env.REACT_APP_API_KEY}`)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setArticles(result.articles);
})
However, when I inspected the network request with Chrome dev tools, you will be able to see the actual value of the API key. I hope this helps folks see how somebody could find an API key on the client even if you store it as an environment variable.
How one could hide an API key:
You could make the HTTP request from your server side logic, so you can safely hide an API key in the .env file. In the below example I created an enpoint to /top-headlines/:searchTerm. Once a request to that endpoint is received, then I send the Axios request to the news API using the "NEWS_API_KEY" environment variable which is stored in my .env file.
route.get("/top-headlines/:searchTerm", async (req, res) => {
const { searchTerm } = req.params;
try {
const articlesResponse = await axios.get(
`https://newsapi.org/v2/top-headlines?q=${searchTerm}&apiKey=${process.env.NEWS_API_KEY}`
);
const articlesData = articlesResponse.data;
res.send(articlesData);
} catch (error) {
console.log(error);
}
});
If you use the API key for local development purposes, put it under the .env.development file and Git ignore it. Credentials in the .env file will be picked up by the build process, which will expose the data in production.
For details, see What other .env files can be used?
Be advised! If you put any credentials in a React client, they are not secure, even if you are using gitignore and an .env file. Still they are not secure.
You should really only save API keys or secrets in your backend, such as Node.js or Express.js. Use a proxy, send the request from the front end to the backend and then the backend will make a request for fetching data to front end.
If you are in production, then you cannot use environment variable directly there for frontend (React). You need to follow the instructions on How to implement runtime environment variables with create-react-app, Docker, and Nginx in order to achieve this goal if you want to access environment variables in production.
The secure key/secret should never be sent to the client side. Say, you want to download a file from S3 down on the client machine via your app (running in a browser).
Make a call to the server to obtain a ephemeral token (which expires with time)
the server (which has the secret and everything) makes the token and sends it back
the client uses the token to access S3
The token itself is not a secret and it's useless once it expires.
Creating a .env file is helpful as stated in previous answers. But one point to notice here is that:
If you are using API_KEY in your URL as state like this,
this.state = {
url:`http://newsapi.org/v2/everything&apiKey=${process.env.REACT_APP_API_KEY}`
}
then it will be visible in React developer tool.
Instead, you can put your API_KEY directly at the location of fetch. For example,
fetch(`http://newsapi.org/v2/everything?&apiKey=${process.env.REACT_APP_API_KEY}`)

windows 10 app development - Mediaplayer

I am using below code to play mp3 file from some url (https://domailname/a.mp3), this server required jwt token for authenticating the request.
how can i play the audio from any url which requires authentication
System.Uri manifestUri = new Uri("https://domailname/a.mp3");
mediaPlayerElement.Source = MediaSource.CreateFromUri(manifestUri);
mediaPlayerElement.MediaPlayer.Play();
You may put the token in the URL as a query parameter if under under the following circumstances described on this thread.
System.Uri manifestUri = new Uri("https://domailname/a.mp3/?jwt=jwttoken");
MediaSource instance can create from AdaptiveMediaSource. If the media is adaptive source you may try to create a AdaptiveMediaSource by CreateFromUriAsync(Uri, HttpClient) method firstly. Put the token as value of Authorization Header using the bear schema, and add the header to HttpClient by the DefaultRequestHeaders property. For this you may reference the scenario 3 of AdaptiveStreaming official sample.

How to generate OAuth2.0 Bearer when calling App Engine Endpoints API?

I am providing a REST API via App Engine. I used Cloud Endpoints to generate it, although the client will not be mobile Android/iPhone but rather a known web server. Since I am familiar with this server (it is part of my application), I decided to use Service Account authorization in order to authorize the API calls (In addition, I will do IP validation, but that's beside the point).
I made all the necessary arrangement, created a Google developer project, generated a service account id (and email), with a p12 file, and added all the annotations needed on the server side (including a User object in the implementing function).
Now I want to implement a call to this API, and in order for it to work, I need to include a proper authorization header in my request.
When working with Google APIs, the client libraries generate some Credential object which you later need to pass in building some Service object, which represents a Google API you wish to call. For example, if you want to access Drive API in Java, you will do:
Drive drive = new Drive.Builder(Globals.httpTransport, Globals.jsonFactory, credential).build();
Where credential object is the object I previously build as follows:
credential = new GoogleCredential.Builder().setTransport(Globals.httpTransport)
.setJsonFactory(Globals.jsonFactory)
.setServiceAccountId(serviceAccountEmail)
.setServiceAccountScopes(scopes)
.setServiceAccountUser(serviceAccountUser)
.setServiceAccountPrivateKeyFromP12File(file(serviceAccountPrivateKeyP12File))
.build();
However, in my case, the client is not calling a Google API, but rather my App Engine REST API. How do I go about generating (or using the credential object I created to obtain) a proper Authorization header?
You can find some documentation in the readme.html file that is generated alongside the bindings, and here.
You can get the following account information in the console, "Apis & Auth", "Credentials". Here you need to paste "Email Address" of the service account. Your #Api annotation should include the account's "Client Id" in the "clientIds" parameter.
String accountEmail = "your-service-account#developer.gserviceaccount.com";
String keyFilePath = "your-key-file.p12";
This is the minimum authorization scope that is required for Cloud Endpoints API. It only allows the app to access the user's e-mail address. Your #Api annotation should list it in the "scopes" parameter.
String emailScope = "https://www.googleapis.com/auth/userinfo.email";
Then you need to create some support objects and the credential. GsonFactory can be replaced with JsonFactory if you prefer.
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GsonFactory gsonFactory = new GsonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(gsonFactory)
.setServiceAccountId(accountEmail)
.setServiceAccountScopes(Collections.singleton(emailScope))
.setServiceAccountPrivateKeyFromP12File(new File(keyFilePath))
.build();
And finally create your API client. Replace YourApi with the client from the generated bindings. If you want to test against the dev AppServer, you can call .setRootUrl(yourDevServerUrl + "/_ah/api") on the builder.
YourApi client = new YourApi.Builder(httpTransport, gsonFactory, credential)
.setApplicationName("YourClientName")
.build();

Resources