authorization not working in swagger jersey? - jersey-2.0

This my index.html file for swagger UI.
$(function () {
window.swaggerUi = new SwaggerUi({
url: "http://localhost:8080/hootout/rest/api-docs",
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function(swaggerApi, swaggerUi){
log("Loaded SwaggerUI");
if(typeof initOAuth == "function") {
/*
initOAuth({
clientId: "your-client-id",
realm: "your-realms",
appName: "your-app-name"
});
*/
}
$('pre code').each(function(i, e) {
hljs.highlightBlock(e)
});
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none"
});
$('#input_apiKey').change(function() {
var key = $('#input_apiKey')[0].value;
log("key: " + key);
if(key && key.trim() != "") {
log("added key " + key);
window.authorizations.add("key", new ApiKeyAuthorization("api_key", key, "query"));
}
})
window.swaggerUi.load();
});
I am implementing swagger UI first time in my project. I am use this index.html file for swagger UI. My swagger UI is working properly but I am not getting authorization for api.
Thank you...

Related

My POST request works on Postman but not with axios

I have a nuxt project deployed on Netlify and now I want to add a newsletter (add a subscriber to my audience on Mailchimp). To achieve that, I've opted to use the AWS serverless lambda functions. To be honest, it's the first time that i've heard about serverless functions. I found this tutorial https://hashinteractive.com/blog/nuxt-js-mailchimp-integration-add-contact-to-list/ and at the end, i've decided to make a test on Postman. I've made a post to http://localhost:8888/.netlify/functions/subscribe and it worked. But when I try the same thing with axios I get the error 405 (method not allowed).
Newsletter.vue
<form #submit.prevent='submitNewsletter' class="newsletter__form" >
<input type="email" placeholder="E-mail" class="newsletter__form-input" v-model="email">
<button class="newsletter__form-button" type="submit">Subscribe</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data(){
return{
email: ''
}
},
methods:{
submitNewsletter(){
axios.post('http://localhost:8888/.netlify/functions/subscribe', { email: this.email}, {
headers: {
methods: 'POST',
'Content-Type':'application/json'
}
})
.then(function (response) {
console.log(response);
}).
catch((error) =>{
console.log('The error:' + error)
})
this.$toasted.success("Thank you for your subscription !!!", {
theme: "toasted-primary",
position: "top-left",
containerClass: 'myContainer',
fitToScreen: true,
fullWidth: true,
duration : 5000
});
}
}
}
</script>
functions > subscribe > subscribe.js
const fetch = require('node-fetch');
const base64 = require('base-64');
exports.handler = async (event, context) => {
// Only allow POST
if (event.httpMethod !== 'POST') {
return { statusCode: 405, body: 'Method Not Allowed' };
}
const errorGen = msg => {
return { statusCode: 500, body: msg };
};
try {
const { email } = JSON.parse(event.body);
console.log(email);
if (!email) {
return errorGen('Missing Email');
}
const subscriber = {
email_address: email,
status: 'subscribed',
};
console.log(subscriber);
console.log(JSON.stringify(subscriber));
const creds = `blooming-thoughts:${process.env.MAILCHIMPS_API_KEY}`;
const response = await fetch(`https://us20.api.mailchimp.com/3.0/lists/${process.env.AUDIENCE_ID}/members/`, {
method: 'POST',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: `Basic ${base64.encode(creds)}`, },
body: JSON.stringify(subscriber),
});
const data = await response.json();
if (!response.ok) {
// NOT res.status >= 200 && res.status < 300
return { statusCode: data.status, body: data.detail };
}
return {
statusCode: 200,
body: JSON.stringify({ msg: "You've signed up to the mailing list!", detail: data, }),
};
} catch (err) {
console.log(err); // output to netlify function log
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }),
};
}
};
My netlify.toml
[build]
publish = "dist"
functions = 'functions'
I've made a push to my repository and netlify built without any error, but when I try to add a newsletter from my site nothing happens.
I've solved my problem. If you're having trouble like I was, follow these steps:
Create a folder called functions in your root directory, then create a index.js (the file name is up to you).
Create a file called netlify.toml and add the following code :
[build]
functions = "functions"
Then, inside your index.js goes the code that will communicate with your API
On the vue component, make a post request to the <your-site>/.netlify/functions/index . You can find the endpoint going to functions on netlify dashbord.
Don't forget to register your env variables on Netlify (Build & Deploy) and that's it.

Sharepoint list item using Api Rest

I need to get a list's items, so I created this function
export function retrieveSPItems(spToken, alias) {
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
var myHeaders = new Headers({
Accept: "application/json;odata=nometadata",
Authorization: spToken,
});
return fetch(url, {
method: "get",
headers: myHeaders,
}).then((response) => response.json());
}
As a output I get 3000.
when I change the url to
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
I get an empty list!
PS :
It's work in Postman with no problem
The token is generated by adaljs :
Get Token
authContext.acquireToken(SP_BASE_URL, function (error, token){....})
Adal config
export const adalConfig = {
tenant: CURRENT_TENANT,
clientId: CURRENT_APP_ID,
endpoints: {
api: CURRENT_APP_ID,
graph: GRAPH_BASE_URL,
sharepoint: SP_BASE_URL,
},
cacheLocation: "localStorage",
validateAuthority: true,
};
So I need to know :
what the reason fot this issue?
How can I fix it?
It's too general information, you need debug and figure out the detailed error information.
My test demo:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="Scripts/adal.js"></script>
<script type="text/javascript">
var authContext = null;
var user = null;
(function () {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'xxx.onmicrosoft.com',
clientId: '9afc37cb-x-x-x-xxx',
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: "https://graph.microsoft.com",
sharePointUri: "https://xxx.sharepoint.com/",
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
//$errorMessage.html(authContext.getLoginError());
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
//authContext.acquireToken(window.config.clientId, function (error, token) {
// console.log('---');
//})
authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
alert(token);
if (error || !token) {
console.log("ADAL error occurred: " + error);
return;
}
else {
var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";
$.ajax({
type: "GET",
url: listUri,
headers: {
"Authorization": "Bearer " + token,
"accept": "application/json;odata=verbose"
}
}).done(function (response) {
console.log("Successfully fetched list from SharePoint.");
var items = response.d.results;
for (var i = 0; i < items.length; i++) {
console.log(items[i].Title);
$("#SharePoint").append("<li>" + items[i].Title + "</li>");
}
}).fail(function () {
console.log("Fetching list from SharePoint failed.");
})
}
})
}());
</script>

How to call http.post using protractor in typescript

I am trying to do http post in protractor. The status of http.post sits in pending status and doesn't return any response.
I am calling a method in onPrepare function under specDone:
jasmine.getEnv().addReporter({
specDone: function(result) {
if (result.status == "failed") {
browser.getCapabilities().then(function(caps) {
var browserName = caps.get("browserName");
browser.takeScreenshot().then(function(png) {
var stream = fs.createWriteStream(
"./reports/screenshots/" +
browserName +
"-" +
result.fullName +
".png"
);
stream.write(new Buffer(png, "base64"));
stream.end();
});
});
}
new PortalData().PushDataToPortal("");
}
});
Below function in called from onPrepare, the API takes the parameter from body. I am using protractor-http-client package for API calls.
export class PortalData {
public PushDataToPortal(result) {
const http: HttpClient = new HttpClient();
const LogFilePathInSharedLocation =
"\\\\10.101.101.11\\temp\\DocStar\\Automation\\TestLogs\\Logs.txt";
http
.post(
someurl,
LogFilePathInSharedLocation,
{ "Content-Type": "application/x-www-form-urlencoded" }
)
.then((response: ResponsePromise) => {
console.log(response);
});
}
Please advise. Thanks!
I would suggest you use Http call in beforeAll instead of onPrepare.
You can try superagent or supertest npm modules:
Example for superagent
const superagent = require('superagent');
// callback
superagent
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
.set('X-API-Key', 'foobar')
.set('accept', 'json')
.end((err, res) => {
// Calling the end function will send the request
});
// promise with then/catch
superagent.post('/api/pet').then(console.log).catch(console.error);
// promise with async/await
(async () => {
try {
const res = await superagent.post('/api/pet');
console.log(res);
} catch (err) {
console.error(err);
}
})();
Example for supertest
const supertest = require('supertest');
const request = supertest(`${baseURL}`);
request.put('/test/sendlocal')
.send(profileAddressData.createData)
.set('Content-Type', 'application/json')
.set('Accept', '*/*')
.expect(200)
.end((err, res) => {
if (err) {
console.error('Error: ', err);
console.error('Response: ', res);
}
});

Linkedin ionic2 authentication

Can anybody help me with Ionic2 LinkedIn authentication without using ionic services, stamplay or AuthO, I have written the code, configured the app on linkedin, but it seems there is a problem with it(configuration) as the LinkedIn Popup opens but doesn't generates any response after entering credentials.
Note : I have used stamplay for linkdin
// install cordova-plugin-inappbrowser
declare var window: any;
export class HomePage {
constructor(public platform: Platform,private http: Http) {
this.platform = platform;
this.http = http;
}
linkedlogin()
{
this.platform.ready().then(() => {
this.linked().then(success => {
//Generate to the access token
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
this.http.get("https://www.linkedin.com/oauth/v2/accessToken?client_id='Your clientID'&client_secret='your client_secret'&redirect_uri=https://ionic-li-login.stamplayapp.com/auth/v1/linkedin/connect&code="+ success + "&grant_type=authorization_code",
options).map( res =>res.json()).subscribe(data =>
{
var accessToken = data.access_token;
//Get to the people data for login user data
this.http.get("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,industry,picture-url,headline,date-of-birth,location:(name))?format=json&oauth2_access_token=" + accessToken )
.map( res =>res.json())
.subscribe(showdata => {
var linkdata = {
id:showdata.id,
firstName:showdata.firstName,
lastName:showdata.lastName,
emailAddress:showdata.emailAddress,
industry:showdata.industry,
headline:showdata.headline,
location:showdata.location.name,
pictureUrl:showdata.pictureUrl,
}
console.log(JSON.stringify(linkdata));
});
});
}, (error) => {
alert('Error');
});
});
}
linked(): Promise<any>
{
return new Promise(function(resolve,reject)
{
/* Linkedin login and signup page */
var browserRef = window.cordova.InAppBrowser.open("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id='your clientID'&redirect_uri=https://ionic-li-login.stamplayapp.com/auth/v1/linkedin/connect&scope=r_basicprofile+r_emailaddress");
browserRef.addEventListener("loadstart", (event) => {
if ((event.url).indexOf("https://ionic-li-login.stamplayapp.com/auth/v1/linkedin/connect") === 0)
{
browserRef.removeEventListener("exit", (event) => {});
browserRef.close();
/* Will be generate to the authentication code */
var authcode = (event.url).split("code=")[1];
if(authcode !=null)
{
resolve(authcode);
}
else
{
alert("Problem authenticating with Linkdin");
}
}
});
browserRef.addEventListener("exit", function(event)
{
reject("The Linkdin sign in flow was canceled");
});
});
}
}

Protractor/Jasmine send REST Call when a test failed

I am using Protractor and Jasmine to test my hybrid mobile app, which works fine. I'd like to create an incident on my Team Foundation Server (TFS), when a test fails. Therefore, I have to send an REST-Call to the Api, which also works fine in my Angular App. But it does not work, when I am inside my test environment.
My Code:
var BrowsePage = require('./browse.page');
var tfsIncident = require('./tfsIncident_service');
var request = require('request');
describe('Testing the browse state', function () {
var browsePage = new BrowsePage();
var specsArray = [];
var reporterCurrentSpec = {
specDone: function (result) {
if (result.status === 'failed') {
var mappedResult = tfsIncident.create(result);
console.log(mappedResult); //This works so far, but then it crashes
var options = {
method: 'PATCH', //THis Method requiered the API
url: 'MY_COOL_API_ENDPOINT',
headers: {
'Authorization': 'Basic ' + btoa('USERNAME' + ':' + 'PASSWORD'),
'Content-Type': 'application/json-patch+json'
},
body: mappedResult
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(response);
console.log(info);
}
}
request(options, callback);
}
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec);
//This test passes
it('should be able to take display the heading', function () {
expect(browsePage.headline.isPresent()).toBe(true);
});
// Test is supposed to fail
it('should be able to fail', function () {
expect(browsePage.headline).toBe(1);
});
// Test is supposed to fail as well
it('should be able to fail too', function () {
expect(browsePage.headline).toBe(2);
});
});
So the problem is, that my only console output is (after the console.log(mappedResult)): E/launcher - BUG: launcher exited with 1 tasks remaining
So I have no idea, why this does not work.
Any help appreciated.
Edit
Protractor: 5.0.0
Appium Desktop Client: 1.4.16.1
Chromedriver: 2.27
Windows 10 64 Bit
Jasmine: 2.4.1
I finally got my problem solved. The problem was caused by ignoring the promises by jasmine. I had to add a .controllFlow().wait() to my protractor.promise
The following code works fine:
var BrowsePage = require('./browse.page');
describe('Testing the browse state', function () {
var browsePage = new BrowsePage();
var reporterCurrentSpec = {
specDone: function (result) {
if (result.status === 'failed') {
//Mapping of the result
var incident = [
{
op: 'add',
path: '/fields/System.Title',
value: 'Test: ' + result.fullName + ' failed'
},
{
op: 'add',
path: '/fields/System.Description',
value: result.failedExpectations[0].message
},
{
op: 'add',
path: '/fields/Microsoft.VSTS.Common.Priority',
value: '1'
},
{
op: 'add',
path: '/fields/System.AssignedTo',
value: 'Name Lastname <e#mail.com>'
}
];
protractor.promise.controlFlow().wait(create(incident)).then(function (done) { //The magic happens in this line
console.log("test done from specDone:" + done);
});
}
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec); //Add new Jasmine-Reporter
function create(incident) {
var request = require('request');
var defer = protractor.promise.defer(); //new promise
request({
url: 'https://MY_COOL_ENDPOINT.COM',
method: "PATCH",
json: true, // <--Very important!!!
headers: {
'Authorization': 'Basic ' + new Buffer('USERNAME' + ':' + 'PASSWORD').toString('base64'),
'Content-Type': 'application/json-patch+json'
},
body: incident
}, function (error, response, body) {
console.log(error);
console.log(response.statusCode);
console.log(body.id); //Id of created incident on TFS
defer.fulfill({
statusCode: response.statusCode
}); //resolve the promise
});
return defer.promise; //return promise here
}
it('should be able to display the heading', function () {
expect(browsePage.headline.isPresent()).toBe(true);
});
it('should be able to fail', function () {
expect(browsePage.headline.isPresent()).toBe(false);
});
it('should be able to fail 2', function () {
expect(browsePage.headline.isPresent()).toBe(false);
});
});
Attention
When the test suite is done and the last promise is not resolved at this moment, the last incident is not created. I'll try to work around by adding to the last test a browser.sleep(5000); so that the create(incident) function gets more time to finish.
Thanks to this StackOverflow answer for helping me.