Rest Assured - Response body verification - rest-assured

I have the below response and I need to validate the body.
Json :
[
"Admin Login",
"Admin Contact",
"Administrator",
"Ads-View"
]
Code :
#Test(groups = {"ITTest"})
public void testAdmin()
{
com.jayway.restassured.response.Response testAdminResponse = get("/Admin");
testAdminResponse.then().assertThat().statusCode(200);
testAdminResponse.then().assertThat().body("$",equalTo("["Admin Login", "Admin Contact", "Administrator", "Ads-View"]"));
}
I tried hamcrest matchers - equalTo, containsString, hasItems, hasItem but all in vain
How do I validate the body completely ?

If you are looking to validate the response as a whole and if you know for certain that the response will be of the below format
[
"Admin Login",
"Admin Contact",
"Administrator",
"Ads-View"
]
Then you can, convert the response as a string and use Assert.assertEquals
Assert.assertEquals(**response**, "[\n" +
" \"Admin Login\",\n" +
" \"Admin Contact\",\n" +
" \"Administrator\",\n" +
" \"Ads-View\"\n" +
"]");
I ran it locally and it works fine for me
RestAssured.baseURI = "http://127.0.0.1:3000/Admin";
String **response** = RestAssured.given().
when().get().then().extract().asString();
Assert.assertEquals(response, "");
System.out.println("Body is : " + response);

Related

Name is null from apple sign in. its a new user, firebase react native

Hi I cannot get the user's name via APPLE SSO.
Im using react native firebase. It logs in fine.
I made sure its a new account for the app.
in firebase console > auth > removed my apple user email.
https://appleid.apple.com/account/manage > sign in with security > sign in with Apple > and "Stop using sign in with apple" on that app. the private relay email matches in firebase and is removed.
how do i get the name from apple SSO?
import auth from '#react-native-firebase/auth';
import { appleAuth } from '#invertase/react-native-apple-authentication';
async function onAppleButtonPress() {
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
});
if (!appleAuthRequestResponse.identityToken) {
throw new Error('Apple Sign-In failed - no identify token returned');
}
const { identityToken, nonce } = appleAuthRequestResponse;
const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
const res = await auth().signInWithCredential(appleCredential);
console.log('res', res) // <-- see next code block
// below, displayname is null, i do see firebase Id, and the private email relay address.
console.log('auth().currentUser?', auth().currentUser )
return res
}
// res response
{
"additionalUserInfo": {
"profile": {
"is_private_email": "true",
"sub": "000630.afe8c07332204888...",
"exp": 1666292000,
"real_user_status": 2,
"iss": "https://appleid.apple.com",
"c_hash": "yXmD5j_37t1F...",
"email_verified": "true",
"aud": "com.mydemo.app",
"iat": 1666205600,\
"email": "kgszm...#privaterelay.appleid.com",
"auth_time": 1666205600,
"nonce": "77e6cd4bfca826abc77a179f15b0a8...",
"nonce_supported": true
},
"username": null,
"providerId": "apple.com",
"isNewUser": true <---- shows its a new user
},
"user": {
"isAnonymous": false,
"emailVerified": true,
"providerData": [
{
"providerId": "apple.com",
"uid": "000630.afe8c0733220488889977a5c9...",
"email": "kgszm...#privaterelay.appleid.com",
} ],
"uid": "4VpWSNUxVAeNzuEu4IQrLKq5Mw43",
"email": "kgszm...#privaterelay.appleid.com",
"refreshToken": "AOEOulaKPm6HzbT....",
"displayName": null, <--- why is this null?
"tenantId": null,
"phoneNumber": null,
"photoURL": null,
"metadata": {
"creationTime": 1666205601897,
"lastSignInTime": 1666205601897
},
"providerId": "firebase"
}
}}'
"#react-native-firebase/auth#^12.9.0": version "12.9.3"
AS described in invertase readme file, apple API provide fullName only the first time, you need to save it in signup the first time.
For testing purpose you can delete using apple account form settings/security and password/delete apple account of your application.
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL],
});
// Create a Firebase credential from the response
const { identityToken, nonce, fullName } = appleAuthRequestResponse;
const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
let fullName_ = '';
if(fullName.namePrefix) fullName_ = fullName_ + fullName.namePrefix + ' ';
if(fullName.givenName) fullName_ = fullName_ + fullName.givenName + ' ';
if(fullName.familyName) fullName_ = fullName_ + fullName.familyName + ' ';
if(fullName.nickname) fullName_ = fullName_ + fullName.nickname + ' ';
if(fullName.middleName) fullName_ = fullName_ + fullName.middleName + ' ';
if(fullName.nameSuffix) fullName_ = fullName_ + fullName.nameSuffix + ' ';

Microsoft Graph API - Schema validation fails for PlanID when creating bucket, and update task doesn't work

First problem:
I am unable to create buckets in Microsoft Planner through the Graph API. I keep getting the following error even though I already specified the correct plan ID:
{"error": {"code": "", "message": "Schema validation has failed. Validation for field 'PlanId', on entity 'Bucket' has failed: A non-null value must be specified for this field.", "innerError": {"date": "2021-04-13T08:21:23", "request-id": "7f73320f-c273-4c8f-aedf-e4c413343d99", "client-request-id": "7f73320f-c273-4c8f-aedf-e4c413343d99"}}}
Second problem:
I am unable to update tasks in Microsoft Planner through the Graph API. I get a 200 response status code, but the actual task on Planner doesn't actually reflect the changes.
import requests_oauthlib
import config
import os
import json
MSGRAPH = requests_oauthlib.OAuth2Session(config.CLIENT_ID,
scope=config.SCOPES,
redirect_uri=config.REDIRECT_URI)
# Enable non-HTTPS redirect URI for development/testing.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Allow token scope to not match requested scope. (Other auth libraries allow
# this, but Requests-OAuthlib raises exception on scope mismatch by default.)
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
os.environ['OAUTHLIB_IGNORE_SCOPE_CHANGE'] = '1'
def call_endpoint(do, **kwargs):
BASE_URL = "https://graph.microsoft.com"
RESOURCE = "v1.0/planner"
headers = {'Authorization': f'Bearer {config.ACCESS_TOKEN}'}
ENDPOINTS = {
"Create Plan": {"URL": f"{BASE_URL}/{RESOURCE}/plans", "data": {'owner': config.GROUP_ID, 'title': kwargs.get('title', "")}},
"Create Bucket": {"URL": f"{BASE_URL}/{RESOURCE}/buckets", "data": {"planId": kwargs.get("planId", ""), "name": kwargs.get("name", ""), 'orderHint': " !"}},
"Create Task": {"URL": f"{BASE_URL}/{RESOURCE}/tasks", "data": {'planId': kwargs.get('planId', ""), 'bucketId': kwargs.get('bucketId', ""), 'title': kwargs.get('title', ""), 'assignments': {}}},
"Get Plans": {"URL": f"{BASE_URL}/v1.0/groups/{config.GROUP_ID}/planner/plans", "data": {}},
"Get Buckets": {"URL": f"{BASE_URL}/v1.0/planner/plans/{kwargs.get('planId', '')}/buckets", 'data': {}},
"Get Tasks": {"URL": f"{BASE_URL}/{RESOURCE}/plans/{kwargs.get('planId', '')}/tasks", "data": {}},
"Get Task": {'URL': f"{BASE_URL}/{RESOURCE}/tasks/{kwargs.get('taskId', '')}/details", "data": {}},
"Get Bucket": {"URL": f"{BASE_URL}/{RESOURCE}/buckets/{kwargs.get('bucketId', '')}", "data": {}},
"Update Task": {'URL': f"{BASE_URL}/{RESOURCE}/tasks/{kwargs.get('taskId', '')}/details", "data": {'title': kwargs.get('title', ''), 'description': kwargs.get('description', ''), 'previewType': 'description'}},
}
endpoint = ENDPOINTS[do]['URL']
data = ENDPOINTS[do]['data']
print(f'{do} at {endpoint} with {data}')
if 'Create' in do:
response = MSGRAPH.post(endpoint, headers=headers, data=data).json()
elif 'Get' in do:
response = MSGRAPH.get(endpoint, headers=headers).json()
elif 'Update' in do:
response = MSGRAPH.get(ENDPOINTS['Get Task']['URL'], headers=headers, data=ENDPOINTS['Get Task']['data']).json()
print(response)
eTag = response['#odata.etag']
headers['If-Match'] = eTag
headers['Prefer'] = "return=representation"
response = MSGRAPH.patch(endpoint, headers=headers, data=data)
print(response)
response = MSGRAPH.get(ENDPOINTS['Get Task']['URL'], headers=headers, data=ENDPOINTS['Get Task']['data']).json()
if 'error' not in response:
print(f"Successful API call: {do}")
else:
print(f"API call {do} failed due to {response['error']}")
return response
response = call_endpoint("Create Bucket", name='wtf', planId='qHfOXBxd5UGoPCaiNOKWBskAE2rj')
response = call_endpoint("Update Task", taskId='IEUy7GJAd0WNTcfLhqXbKMkAIvYH', title="title created by API", description="description created by API")
Any suggestions would be deeply appreciated.
Just to isolate the issue we tried the same API call and its working with Microsoft Graph Explorer.
You found that you need to json.dumps(data) and add the "Content-Type": "application/json" into the header for it work.

MS Graph Get User with Expand=Extensions return status 500

Getting the user just passing the user id works fine:
const { data: response } = await axios.get(`${ MS_GRAPH_USER_API }/${ id }`, {
headers: {
Authorization: `Bearer ${ TOKEN }`,
"Content-Type": "application/json"
}
})
However, this:
const { data: response } = await axios.get(`${ MS_GRAPH_USER_API }/${ id }?$expand=extensions`, {
headers: {
Authorization: `Bearer ${ TOKEN }`,
"Content-Type": "application/json"
}
})
returns the following error:
data: '{"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users(extensions())/$entity"{\r\n' +
' "error": {\r\n' +
' "code": "InternalServerError",\r\n' +
"message": "The entity instance value of type 'microsoft.graph.user' doesn't have a value for property 'id'. To compute an entity's metadata, its key and concurrency-token property values must be provided.",\r\n +
' "innerError": {\r\n' +
' "date": "2020-12-19T09:51:26",\r\n' +
' "request-id": "93cf5d97-0096-4769-871e-f8fcf7cd17c3",\r\n' +
' "client-request-id": "93cf5d97-0096-4769-871e-f8fcf7cd17c3"\r\n' +
' }\r\n' +
' }\r\n' +
'}'
Why is that? The user has an extension added to his/her profile.
Seems like you need to include a select clause in the URL before the expand clause, i.e.:
$select=businessPhones,displayName,givenName,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,id&$expand=extensions
just had to try a few different google searches before finding this:
why does Microsoft Graph require $select with $expand=extensions?

Basic Authorization Angular 5 get Response for preflight has invalid HTTP status code 401

I am requesting for an access_token using Basic Authorization in Angular but I get this error.
I tried it in Postman and it has no problem at all.
I am using a service to post a request from API.
requestToken() {
var encoded: string = btoa("my-username" + ":" + "my-password")
let options = {
username: 'username',
password: 'password',
grant_type: 'password',
}
let _httpHeader = new HttpHeaders();
_httpHeader = _httpHeader.append("Content-Type", "application/x-www-form-urlencoded");
_httpHeader = _httpHeader.append("Authorization", "Basic " + encoded);
return this._http.post(API_URL + '/oauth/token?grant_type=' + options.grant_type + '&password=' + options.password + '&username=' + options.username, { headers: _httpHeader, withCredentials: true });
}
Then call that service in my component to save it in session storage.
this._dataService.requestToken()
.subscribe(
res => {
sessionStorage.setItem('access_token', res['access_token']);
sessionStorage.setItem('refresh_token', res['refresh_token']);
},
err => {
console.log('Authentication failed!');
}
);

401 Permission Error with Balanced Payments

I'm using Parse.Cloud.httpRequest and I need to send basic authentication with only a username to balanced payments. Where does this go and what would that look like? I tried setting it in the Headers but that's not working.
Parse.Cloud.httpRequest({
method:'POST',
url: customerUrl,
headers:{
"Content-Type" : "application/x-www-form-urlencoded",
"Accept" : "application/vnd.api+json;revision=1.1",
"Authorization" : balancedSecret
},
body:bodyJsonString,
success: function(httpResponse) {
console.log(httpResponse.text);
response.success(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(httpResponse.text);
}
});
When I call the function I get:
"errors": [
{
"status": "Unauthorized",
"category_code": "authentication-required",
"description": "Not permitted to perform create on customers. Your request id is OHMca9c440a0a7811e4ba9202a1fe52a36c.",
"status_code": 401,
"category_type": "permission",
"request_id": "OHMca9c440a0a7811e4ba9202a1fe52a36c"
}
]
"Authorization" : balancedSecret
This is going to be wrong. You use the secret as the username, and nothing as the password. You then concatenate them together, base64 encode them, and pass that as the value of the auth header.
I don't have the setup to double check this, but this should work as the value:
"Basic " + encodeBase64(balancedSecret + ":")
Giving this code:
authHeader = "Basic " + btoa(balancedSecret + ":")
Parse.Cloud.httpRequest({
method:'POST',
url: customerUrl,
headers:{
"Content-Type" : "application/x-www-form-urlencoded",
"Accept" : "application/vnd.api+json;revision=1.1",
"Authorization" : authHeader
},
body:bodyJsonString,
success: function(httpResponse) {
console.log(httpResponse.text);
response.success(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(httpResponse.text);
}
});

Resources