How to use basic authentication with Rest Assured in this situation - api

I am trying to use authentication with RestAssured.
Here is my code that does not work:
public static void authenticate(){
RestAssured.baseURI = "https://randomUrl/login";
RequestSpecification request = RestAssured.given().auth().basic("user#google.com", "password123");
Response response = request.get();
System.out.println(response.asString());}
A big reason for which this does not work is that I am missing certain things because when i look at the actual request in postman, there is more info in the tabs there as follows:
Authorization: Basic Auth:
Username:"client"
Password:"pass"
Headers:
Authorization: Basic Y2xpZW50OnBhc3N3b3Jk
Content-Type: application/x-www-form-urlencoded
Body:
username:"user#google.com"
password:"password123"
grant_type:"password"
My question is what are the missing pieces in my code and how do integrate them so that the authorization works?
Thank you

REST Assured doesn't send the credentials when using basic auth unless it's challenged by the server. If the server doesn't challenge, it won't send it. I this is the case you can use preemptive basic auth:
RestAssured.given().auth().preemptive().basic("user#google.com", "password123")

I hope below code can help you to resolve authentication issue
given().relaxedHTTPSValidation().auth().preemptive().basic("username", "token(in base 64 encryption")

Related

Authorizing API Requests to 3rd Party Services in Mongodb Realm

I'm building a React app that allows users to login with Google and then connects to a webhook/3rd Party service in Realm. The service should only return data that the users own.
I've set up the OAuth 2 with Google and can get back access_token for a user and I then pass it in the header (I've also tried the URL params) to the webhook. But I get an error back saying:
400 "no authentication methods were specified" - "Invalid Parameter".
After much testing, I've identified that it must be a Realm issue - but I can't figure out what.
I've tried authenticating with Google in Postman and sending a request from there like this:
GET <incoming_webhook URL>
Request Headers
Authorization: Bearer <access_token>
User-Agent: PostmanRuntime/7.26.10
Accept: */*
Host: us-east-1.aws.webhooks.mongodb-realm.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
But I get the same error.
In Realm I have "Google" enabled as an authentication providers (and the authentication works just not the authorization through the webhook).
Per https://docs.mongodb.com/realm/services/configure/service-webhooks/#configure-user-authentication, you can choose email/password, an API key, or a custom JWT token. I don't know whether you can use google login directly to a webhook, but you're probably better off making a realm function instead.
Regarding the error no authentication methods were specified, you can specify the type of authentication method (using a custom JWT as an example) by either:
putting it in the header:
Header: jwtTokenString, Value: eyJhbGci.....
OR
by including it as part of the webhook body:
{
"jwtTokenString":"eyJhbGci...",
"mydata": "my data value"
}
If you try to use both methods, you get a multiple authentication methods used error. HTTP Bearer tokens in the header, etc, are useless here.
For an API Key, instead of jwtTokenString, use api-key; or email`password` for email\password authentication.
I found these methods of providing authenticating information really unintuitive and the documentation very unclear.

Yii2: HttpClient authorization header not being send

I am working with an API that works well when consumed from Postman:
But when i try to consume it from Yii2 i get {"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401} and i think i am sending all the headers
The authorization was made with a Bearer Token:
Don't know what i am doing wrong, thanks in advance.
I just got that i have to add my headers this way:
Was adding them the wrong way.

Putting a react-django staging site behind basic auth, but auth clashes with token auth for endpoints

Whats the situation?
I've got staging site which is built with Django + React.
Parts of the API you have to login to access. I'm using Django's token authentication for that.
I then wanted to put the entire site behind basic auth, to prevent anyone of accidentally stumbling across it.
What's the problem?
This means I need to pass two authentication methods with my requests. This is possible as described here.
Authorization: Token lksdjf893kj2nlk2n3rl2dOPOnm, Basic YXNkZnNhZGZzYWRmOlZLdDVOMVhk
The token is set in my JS code after being provided to the user when they login in.
Basic authentication is triggered on the first page load, after this the browser stores it and I believe automatically appends it onto any requests where the server has the following header:
WWW-Authenticate: basic
I have configured Django to return the following header:
WWW-Authenticate: basic, token
This successfully causes a XHR request sent via axios to have the basic header appended, when the Authorization header is empty.
The problem is the Authorization header isn't empty, because I need to set a token value in there.
const axiosConfig = {
method: requestType,
url: `${url}`,
withCredentials: true,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
data: payload
};
// If we're logged in then send our auth token
if (localStorage.auth_token) {
// Axios can't see the basic authentication header here so we can't append.
console.log(axiosConfig.headers.Authorization);
// Basic auth will only get sent if I don't set anything here
axiosConfig.headers.Authorization = `Token ${localStorage.auth_token}`;
}
At this point the browser doesn't seem to append the basic header anymore and so my authentication fails.
Is there a way around this?
I wanted a blanket basic auth because there's no way I can accidentally expose anything on staging, otherwise I have to rely entirely on the token authentication and robots.txt which is less than ideal.
The answer in the end was port forwarding.
I removed basic auth, turned off ports 80 and 443 and then used port forwarding to map my SSH to local host.
i.e. ssh -N -L 8755:127.0.0.1:443 user#ip_address

Set HTTP requests defaults in IntelliJ HTTP request client editor

In IntelliJ http request editor; is there a way to set the common config for all the requests in the file (and globally) ?
For example I would like to specify an authorization header for all the requests.
Current code
GET http://localhost:8080/api/foo
Authorization: Bearer my-token
The code I am trying to achieve:
Desirable code
<common headers>
Authorization: Bearer my-token
GET http://localhost:8080/api/foo
GET http://localhost:8080/api/bar
GET http://localhost:8080/api/baz
It's a bit late but i will try to give an answer in case someone is coming around.
I'm not sure it is exactly what you are looking for but maybe it help.
If you are getting your token dynamically from a login endpoint, you can store the token in a variable and use it later in any request.
Exemple:
### Login
POST http://localhost:8080/login
Content-Type: application/json
{
"email": "someEmail",
"password": "somePassword"
}
> {%
client.global.set("auth_token", response.headers.valuesOf('x-auth-token')[0]);
%}
### Get user
GET http://localhost:8080/user/someUserId
Authorization: Bearer {{auth_token}}
In this case, i store my token coming from the header x-auth-token in a variable auth_token. Than i use it in the authorization header for all my next requests.
Found from the official JetBrains website HTTP response handling exemples
Have a nice day!

Sending JWT token in the headers with Postman

I'm testing an implementation of JWT Token based security based off the following article. I have successfully received a token from the test server. I can't figure out how to have the Chrome POSTMAN REST Client program send the token in the header.
My questions are as follows:
1) Am I using the right header name and/or POSTMAN interface?
2) Do I need to base 64 encode the token? I thought I could just send the token back.
For the request Header name just use Authorization.
Place Bearer before the Token. I just tried it out and it works for me.
Authorization: Bearer TOKEN_STRING
Each part of the JWT is a base64url encoded value.
Here is an image if it helps :)
Update:
The postman team added "Bearer token" to the "authorization tab":
I am adding to this question a little interesting tip that may help you guys testing JWT Apis.
Its is very simple actually.
When you log in, in your Api (login endpoint), you will immediately receive your token, and as #mick-cullen said you will have to use the JWT on your header as:
Authorization: Bearer TOKEN_STRING
Now if you like to automate or just make your life easier, your tests you can save the token as a global that you can call on all other endpoints as:
Authorization: Bearer {{jwt_token}}
On Postman:
Then make a Global variable in postman as jwt_token = TOKEN_STRING.
On your login endpoint:
To make it useful, add on the beginning of the Tests Tab add:
var data = JSON.parse(responseBody);
postman.clearGlobalVariable("jwt_token");
postman.setGlobalVariable("jwt_token", data.jwt_token);
I am guessing that your api is returning the token as a json on the response as:
{"jwt_token":"TOKEN_STRING"}, there may be some sort of variation.
On the first line you add the response to the data varibale.
Clean your Global
And assign the value.
So now you have your token on the global variable, what makes easy to use Authorization: Bearer {{jwt_token}} on all your endpoints.
Hope this tip helps.
EDIT
Something to read
About tests on Postman: testing examples
Command Line: Newman
CI: integrating with Jenkins
Nice blog post: master api test automation
Here is how to set token this automatically
On your login/auth request
Then for authenticated page
I had the same issue in Flask and after trying the first 2 solutions which are the same (Authorization: Bearer <token>), and getting this:
{
"description": "Unsupported authorization type",
"error": "Invalid JWT header",
"status_code": 401
}
I managed to finally solve it by using:
Authorization: jwt <token>
Thought it might save some time to people who encounter the same thing.
If you wish to use postman the right way is to use the headers as such
key: Authorization
value: jwt {token}
as simple as that.
Open postman.
go to "header" field.
there one can see "key value" blanks.
in key type "Authorization".
in value type "Bearer(space)your_access_token_value".
Done!
For people who are using wordpress plugin Advanced Access Manager to open up the JWT Authentication.
The Header field should put Authentication instead of Authorization
AAM mentioned it inside their documentation,
Note! AAM does not use standard Authorization header as it is skipped
by most Apache servers. ...
Hope it helps someone! Thanks for other answers helped me alot too!!
Everything else ie. Params, Authorization, Body, Pre-request Script, Tests is empty, just open the Headers tab and add as shown in image. Its the same for GET request as well.
I did as how moplin mentioned .But in my case service send the JWT in response headers ,as a value under the key "Authorization".
Authorization →Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpbWFsIiwiZXhwIjoxNDk4OTIwOTEyfQ.dYEbf4x5TGr_kTtwywKPI2S-xYhsp5RIIBdOa_wl9soqaFkUUKfy73kaMAv_c-6cxTAqBwtskOfr-Gm3QI0gpQ
What I did was ,make a Global variable in postman as
key->jwt
value->blahblah
in login request->Tests Tab, add
postman.clearGlobalVariable("jwt");
postman.setGlobalVariable("jwt", postman.getResponseHeader("Authorization"));
in other requests select the Headers tab and give
key->Authorization
value->{{jwt}}
Somehow postman didn't work for me.
I had to use a chrome extension called RESTED which did work.
In Postman latest version(7++) may be there is no Bearer field in Authorization
So go to Header tab
select key as Authorization and in value write JWT
x-access-token on headers works for me.
key: x-access-token
value: token