No Host in request URL for Grafana datasource plugin tutorial - Add authentication - authentication

I'm trying to follow the example for developing a datasource plugin from Grafana. Ultimately I want my plugin to use Oauth, but even with just the basic Grafana datasource proxy example I seem to be having issues.
I have updated my plugin.json, class and constructor.
I have setup this hard coded example.
in plugin.json
{
"path": "grafana",
"url": "https://github.com"
}
],
And a sample testDataSource()
async testDatasource() {
return getBackendSrv()
.datasourceRequest({
url: this.url + '/grafana/grafana',
method: 'GET',
})
.then(response => {
if (response.status === 200) {
return { status: 'success', message: 'Data source is working', title: 'Success' };
} else {
return { status: 'failure', message: 'Data source is not working: ' + response.status, title: 'Failure' };
}
});
}
When I try and save/test this datasource to call that method, I get in the frontend a
HTTP Error Bad Gateway
And in the logs
t=2021-09-17T14:31:22+0000 lvl=eror msg="Data proxy error" logger=data-proxy-log userId=1 orgId=1 uname=admin path=/api/datasources/proxy/9/grafana/grafana remote_addr=172.17.0.1 referer=http://localhost:3000/datasources/edit/9/ error="http: proxy error: http: no Host in request URL"
I would've expected the request to be routed to the datasource proxy and for that to make the request to github but it seems Grafana is making a request to /api/datasources/proxy/9/grafana/grafana and nothing is picking it up?

Looking up my datasource via API, there's nothing listed for URL.
You will need to render this in your ConfigEditor.tsx
<DataSourceHttpSettings
defaultUrl="http://localhost:8080"
dataSourceConfig={options}
onChange={onOptionsChange}
/>
Which will give you the basic form with URL, whitelist, auth options that you see on most plugins. The URL there I guess should match what you have in your routes.

Related

Google Strategy NestJS

I have this issue, I think I've explored all the internet for it, I'm trying to implement an authentification with passport-google-oauth20 in NestJS.
I got an event click from the front then it goes in the first part of the code
#UseGuards(GoogleAuthGuard)
public async loginGoogle(#Req() req: any) {
}
thens it goes ine the GoogleAuthGuard Part :
constructor() {
super({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: 'http://localhost:5000/redirect',
scope: ['email', 'profile'],
});
// super({ usernameField: 'token' });
}
But in the network console part of the browser I got a CORS error 402 after a redirect 302.
Request URL: http://localhost:3000/redirect
Request Method: GET
Status Code: 302 Found
Remote Address: 127.0.0.1:3000
Referrer Policy: strict-origin-when-cross-origin
Request URL: https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fredirect&scope=email%20profile&client_id=[MyID].apps.googleusercontent.com
Request Method: OPTIONS
Status Code: 405
Remote Address: 216.58.204.109:443
Referrer Policy: strict-origin-when-cross-origin
I already tried to enable all type of cors :
app.enableCors({
origin: ['http://localhost:5000', 'http://localhost:3000'],
allowedHeaders: ['content-type'],
credentials: true,
preflightContinue: false,
optionsSuccessStatus: 204,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
// exposedHeaders: '*',
});
I already configured the redirection on googleapis to allow this one too. I'm out of solution if anyone could help on it, it would be really appreciated.
It feels like the Authentification is good but when it's time to redirect something goes wrong and I can't put headers in the redirect.

NUXT Redirect issue when making a POST request to external API

I have a form that I built in Nuxt. I'm trying to submit it to an external API. The expected response is a JWT token.
async login() {
const res = await this.$axios.$post(`/api/token`, {
username: this.username,
password: this.password
}, this.headers )
console.log(res)
}
Trying to call the API directly gets me a CORS error, so I use proxy settings in my nuxt.confix.js.
...
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
baseURL: '/',
proxy: true
},
proxy: {
'/api/': { target: 'https://<apiurl>.com/', changeOrigin: true }
},
...
Now when I check the network tab, it shows a 301 redirect, but the data that was sent in the post request gets thrown away, and it makes a get request to the API which returns a 405 error (because it's expecting a POST request with a data and not an empty GET request).
How can I make a POST request to an external API using NUXT? Is this an option at all?
I tried changing changeOrigin: false, and that seems to get rid of the issue, but it throws a 500 server error instead and an npm error that says
ERROR [HPM] Error occurred while proxying request localhost:3000/api/token to https://<apiurl>.com/ [ERR_TLS_CERT_ALTNAME_INVALID] (https://nodejs.org/api/errors.html#errors_common_system_errors)
Thank you
The problem is not how to send api to an external API ... the problem is in the external API it self ... make sure the external API has no credentials required to make any action ...
if you can make a request to https://jsonplaceholder.typicode.com/posts and get results that means there is no problems in your code ... cors erros in most cases are backend issue ... which means .. the backend developer who worked on it should fix it

How to send an additional request to endpoint after each test case

I’m currently looking at Botium Box, and I’m wondering if it is possible to send an additional request to our endpoint after each test case? Let me give you some background information about how we set up the HTTP(S)/JSON connector in Botium Box and how we are sending information to our bot:
HTTP(S) endpoint:
https://MyChatBotsEndpoint.com/?userinput={{msg.messageText}}
HTTP method: POST
We also send cookies through the header template in the request builder. Like this:
{
"Cookie": "JSESSIONID={{context.sessionId}}"
}
The response is given back in JSON.
When a test ends (when it is successful but also when it fails), we need to send an additional request to our endpoint. The endpoint URL of that request should look like this:
https://MyChatBotsEndpoint.com/endsession
The header should include the cookie as described before.
Is there a way to achieve this in Botium?
Botium has many extension points to plug in your custom functionality. In this case, I guess the SIMPLEREST_STOP_HOOK is the best choice.
Write a small javascript file calling your endpoint, and register is with the SIMPLEREST_STOP_HOOK capability in botium.json. The context (session context from the HTTP/JSON connector) is part of the hook arguments.
in botium.json:
...
"SIMPLEREST_STOP_HOOK": "my-stop-hook.js"
...
my-stop-hook.js:
const request = require('request')
module.exports = ({ context }) => {
return new Promise((resolve, reject) => {
request({
method: 'GET',
uri: 'https://MyChatBotsEndpoint.com/endsession',
headers: {
Cookie: "JSESSIONID=" + context.sessionId
}
}, (err) => {
if (err) reject(err)
else resolve()
})
})
}

Using the Rally API to pull user profile

I am trying to use the Rally web service API to get some data. Code as blow. On IE it will pop out a login window, after entry login name and password, I am about to get some data. But when I use chrome, it response 401, not sure what I missing. I know there is SDK available, but due to some limitation, not able to use it. Any suggestions please?
var url = https://rally1.rallydev.com/slm/webservice/v2.0/users;
$.ajax({
url: url,
type: 'GET',
heards: { zsessionid: apiKey },
success: function(json) {
console.log(JSON.stringify(json));
}
},
error: function( req, status, err ) { console.log( 'something went wrong', status, err );
}
});
I'd love to know more about why you can't use the SDK. Anyway, in this case your config likely needs headers instead of heards to pass the api key.

Angular 2 AuthHttp with jwt not connecting

I'm trying to use jwt's authHttp to set an API connection to a particular Back End. I'm trying to make it first without any token so I can test it but it seams like it's not even getting connected. I'm using it as following:
this.authHttp.get('localhost:3001/api/basic')
.subscribe(
data => console.log("data"),
err => console.log(err),
() => console.log('Request Complete')
);
The error I'm getting in the console is AuthHttpError {}
I've set my ngModules as it say in the guide:
providers: [
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
}
And
function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({noTokenScheme : true}), http);
}
The thing that drive's me crazy is that using http it works fine like this:
this.http.get('http://localhost:3001/api/basic').subscribe(
data=> console.log(data),
error=> console.log("Getting Error")
);
You are probably thinking "Why he is not using http then instead of authHttp?". Well, that's because setting a heather "Authorization" and its token seams impossible with http.
Any help or guidance would be extremely helpful.
If you don't need JsonWebTokens but simply want to add custom headers, you can do it this way without having to import the angular2-jwt library :
In your service :
private customHeaders: Headers = this.setCredentialsHeader();
setCredentialsHeader() {
let headers = new Headers();
let credentials = window.localStorage.getItem('credentials2');
headers.append('Authorization', 'Basic ' + credentials);
return headers;
}
someMethod() {
let url = 'your.URL.to.API';
return this.http
.get(url, { headers: this.customHeaders })
.map(result => {
console.log(result);
});
}
This way you can add your Authorization header with the type of data you want.
If it's a Authorization Bearer type header you are looking for and use it with angular2-jwt, you can use the default configuration first before trying to provide your own AuthHttp instance through the factory. It will be much simpler to debug and figure where the problem is.
From the documentation : https://github.com/auth0/angular2-jwt#configuration-options
AUTH_PROVIDERS gives a default configuration setup:
In your module with your service, just import the AUTH_PROVIDERS like this :
import { AUTH_PROVIDERS } from 'angular2-jwt';
...
#NgModule({
...
providers: [
AUTH_PROVIDERS,
...
]
})
and simply use the AuthHttp instance in your service like you did.
You should see in the Navigator Network tab your headers being added to your request.
EDIT :
As stated in the documentation, it is appending the token value in the headers from the Token Getter Function defined in the AUTH_PROVIDERS by default.
You therefore need to add your JWT in your LocalStorage with the default name id_token.
To give you my working example, I'm setting a JWT upon the authentication process, where I get a JWT as a response from my Http Call :
auth.service.ts
this.identityService.setToken(token.accessToken);
identity.service.ts
setToken(token?) {
if (token) {
window.localStorage.setItem('id_token', token);
} else {
window.localStorage.removeItem('id_token');
}
}
You should be able to see your JWT in your network tab if done correctly.
Afterwards, the AuthHttp instance should add the headers to your requests as intended...
It might not work correctly if your Token is not a JWT. To check if it's a good one, you can use a website such as https://jwt.io/ where it will be decoded.
If it's still not working, this means the problem is coming from elsewhere. A service not provided correctly, etc.