OpenID-Connect-Java-Spring-Server CORS Disabled ERROR - javascript

I just started using oidc-client-js, so i am really confused trying to understand it . I have the below question :) .
I have been connected to a remote webserver running OpenIDConnect and specifically using https://github.com/mitreid-connect/OpenID-Connect-Java-Spring-Server i have builded the openid-connect-server-webapp and created a client correctly. It is hosted on a vm .
I followed this tutorial -> link
Link of 3 html files i modified for the tutorial i followed ->
here
The error that is shown on the console:
All good as you can see on the image below , i authorized the simple javascript app and i am getting back the access_token along with id_token , though when i am trying to call the API , boom i get error and i don't know why ?
The html index code i have is ( in case it helps you ) :
<!DOCTYPE html>
<html>
<head>
<title>JS Application</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" />
<style>
.main-container {
padding-top: 70px;
}
pre:empty {
display: none;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">JS Application</a>
</div>
</div>
</nav>
<div class="container main-container">
<div class="row">
<div class="col-xs-12">
<ul class="list-inline list-unstyled requests">
<li>Home</li>
<li><button type="button" class="btn btn-default js-login">Login</button></li>
<li><button type="button" class="btn btn-default js-call-api">Call API</button></li>
<li><button type="button" class="btn btn-danger js-logout">Logout</button></li>
</ul>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">User data</div>
<div class="panel-body">
<pre class="js-user"></pre>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">API call result</div>
<div class="panel-body">
<pre class="js-api-result"></pre>
</div>
</div>
</div>
</div>
</div>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.js"></script>
<script src="node_modules/oidc-client/dist/oidc-client.js"></script>
<script>
// helper function to show data to the user
function display(selector, data) {
if (data && typeof data === 'string') {
data = JSON.parse(data);
}
if (data) {
data = JSON.stringify(data, null, 2);
}
$(selector).text(data);
}
var settings = {
authority: 'http://snf-761523.vm.okeanos.grnet.gr:8080/openid-connect-server-webapp',
client_id: 'client',
client_secret: "secret",
user_id: "user",
popup_redirect_uri: 'http://localhost/jsApp/popup.html',
silent_redirect_uri: 'http://localhost/jsApp/silent-renew.html',
post_logout_redirect_uri: 'http://localhost/jsApp/index.html',
response_type: 'token id_token',
scope: 'openid profile email offline_access',
filterProtocolClaims: false
};
var manager = new Oidc.UserManager(settings);
var user;
Oidc.Log.logger = console;
manager.events.addUserLoaded(function (loadedUser) {
user = loadedUser;
display('.js-user', user);
});
manager.events.addSilentRenewError(function (error) {
console.error('error while renewing the access token', error);
});
manager.events.addUserSignedOut(function () {
alert('The user has signed out');
});
$('.js-login').on('click', function () {
manager
.signinPopup()
.catch(function (error) {
console.error('error while logging in through the popup', error);
});
});
$('.js-call-api').on('click', function () {
var headers = {};
if (user && user.access_token) {
headers['Authorization'] = 'Bearer ' + user.access_token;
}
$.ajax({
url: 'http://snf-761523.vm.okeanos.grnet.gr:8080/openid-connect-server-webapp/api/tokens/access',
method: 'GET',
dataType: 'json',
headers: headers
}).then(function (data) {
display('.js-api-result', data);
}).catch(function (error) {
display('.js-api-result', {
status: error.status,
statusText: error.statusText,
response: error.responseJSON
});
});
});
$('.js-logout').on('click', function () {
manager
.signoutRedirect()
.catch(function (error) {
console.error('error while signing out user', error);
});
});
</script>
</body>
</html>

There is a temporary solution tough only for testing your application and not for production , disabling Web-Security on Google Chrome
FIRST YOU NEED TO KILL ALL THE INSTANCES OF CHROME , then install a Plugin Called CORS Toggle
and finally run the bellow commants from Terminal or Commant Prompt
For Windows
.\chrome --args --disable-web-security --user-data-dir
For Ubuntu Linux (tested only there)
/opt/google/chrome/google-chrome --args --disable-web-security --user-data-dir

Related

Alternative to then() function

I'm working on a project that requires a PayPal payment gateway. I found a simple tutorial online that works fine, with the exception that the PayPal Response is sent to the console log. Looking online for any instance were the then() function is used for other than logging to console came up empty. The present code:
return actions.order.capture().then(function (details) {
console.log(details);
needs to be changed, to a function other than then() in order to send the JSON object to the PHP processing page. Being a backend developer, I'm not sure what function that will be. Can anyone make a suggestion please? The entire code is as follows:
The HTML & JS Script
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Paypal Payment</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main id="cart-main">
<div class="site-title text-center">
<h3 class="font-title">Shopping Cart</h3>
</div>
<div class="container">
<div class="grid">
<div class="col-1">
<div class="flex item justify-content-between">
<div class="flex">
<div class="img text-center">
<img src="./assets/pro1.png" alt="">
</div>
<div class="title">
<h3>Canon EOS 1500D</h3>
<span>Electronics</span>
<div class="buttons">
<button type="submit"><i class="fas fa-chevron-up"></i> </button>
<input type="text" class="font-title" value="1">
<button type="submit"><i class="fas fa-chevron-down"></i> </button>
</div>
Save for later |
Delete From Cart
</div>
</div>
<div class="price">
<h4 class="text-red">$349</h4>
</div>
</div>
</div>
<div class="col-2">
<div class="subtotal text-center">
<h3>Price Details</h3>
<ul>
<li class="flex justify-content-between">
<label for="price">Products ( 1 item ) : </label>
<span>$399</span>
</li>
<li class="flex justify-content-between">
<label for="price">Delivery Charges : </label>
<span>Free</span>
</li>
<hr>
<li class="flex justify-content-between">
<label for="price">Amout Payble : </label>
<span class="text-red font-title">$399</span>
</li>
</ul>
<div id="paypal-payment-button">
</div>
</div>
</div>
</div>
</div>
</main>
<script src="https://www.paypal.com/sdk/js?client-id=ASbdZ8CH5kN5y98rzOuKMLPYsHl4QHLYcDGJ6lgaRjxiRp97t53sPWr1yG5vyd9mlHbyqw3vGUZaJsok&disable-funding=credit,card"></script>
<script>
// Create a Global var - the HTML charge is dummy stuff
window.charge = 0.27;
paypal.Buttons({
style : {
color: 'blue',
shape: 'pill'
},
createOrder: function (data, actions) {
return actions.order.create({
purchase_units : [{
amount: {
value: window.charge
}
}]
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
console.log(details);
window.location.replace("https://localhost/PayPal_Simple/payPalResponse.php?q=good");
window.alert('This was successful.');
})
},
onCancel: function (data) {
window.location.replace("https://localhost/PayPal_Simple/payPalResponse.php?q=bad");
window.alert('Something went wrong!');
}
}).render('#paypal-payment-button');</script>
</body>
</html>
The PHP
<?php
// Get the Response from PayPal
$status = $_GET['q'];
// Once there is an object that can be tested, that will be used instead of ?q=
if($status = "good") {
echo "The payment was a success.<br />";
} elseif($status = "bad") {
echo "The charge was cancelled.";
} else {
echo "Something else went wrong.";
}
// Of course, this doesn't display anything
echo '<pre>';
print_r($_POST);
echo '<pre>';
// Insert data into the database
// Redirect the client to another page
?>
Thanks so much in advance for your help!
Cheers,
Rick
Do not capture on the client side and then send data to a backend. Instead, change to a proper server-side integration--the backend should be communicating with PayPal itself and sending data to the client on request.
Make two routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return only JSON data (no HTML or text). The latter one should (on success) store the payment details in your database before it does the return (particularly purchase_units[0].payments.captures[0].id, the PayPal transaction ID)
Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server
As This link reads , try using
onApprove
''''
const onApprove= new Promise((resolve, reject) => {
{resolve((data,actions) => {actions.order.capture(data,actions)}});
});
''''
buttonPushFunction
''''
async function doYourButtonPush() {
try {
await onApprove;
console.log("The Promise is resolved!", value);
} catch (e) {
console.error("The Promise is rejected!", error);
} finally {
function (details) {
console.log(details);
window.location.replace("https://localhost/PayPal_Simple/payPalResponse.php?q=good");
window.alert('This was successful.');
}
}
}
''''

Vue.js on click method , not working on laravel project

As the code below , the vue.js component works correctly , but the on-click method does not work at all and there is no cached errors . it seems that the function does not get called . When webpack is disabled , the code works correctly.
The HTML code :
<div class="row my-4">
<div class="col-8">
<h5>{{price}} $$</h5>
</div>
<div class="col-4">
<button type="button" v-on:click="inquiry" class="btn btn-yui mx-auto btn-block">price</button>
</div>
</div>
Vue.js section
methods: {
inquiry: function(){
axios.post(`http://localhost:8000/api/brand/panel/get/price/plan`,this.form,{
headers: {'Accept': 'application/json'}
})
.then(response => {
this.price = response.data;
})
.catch(function (error) {
console.log(error);
});
},
You use
<script src="{{ asset('js/app.js') }}" defer></script>
or no need to mix or something under app.blade.php files.This line default call layouts/app.blade.php
it's work for me.
Thank you.

Electron child window doesn't want to call its own js script

I'm very much not a javascript person, but I've been making an Electron GUI, and I'm getting confused by why I can't seem to make a child browser window call its own js.
I have a main.js that does a bunch of things, setting up a tray menu, one option of which will spawn a browser window like this:
window = new BrowserWindow({
width: 360,
height: 320,
backgroundColor: "#D6D8DC",
show: false
})
window.setMenuBarVisibility(false);
window.loadURL(require('url').format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
And that window loads fine, and includes this reference to its own window.js, which is the way I've seen it done in Electron examples:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Radiam Agent</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
</head>
<body>
<div id="container" class="container-fluid">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
<h3>Username</h3>
<input name="username" id="username" type="text" size="40"/>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
<h3>Password</h3>
<input name="password" id="password" type="password" size="40"/>
</div>
</div>
<br/><br/>
<div class="button">
<button id="login">Get Radiam Login Token</button>
</div>
</div>
<script src="window.js" charset="utf-8"></script>
</body>
</html>
But the window.js code, which looks like this (the entire file), doesn't seem to fire ever:
const notifier = require("node-notifier");
const zerorpc = require("zerorpc");
let client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
function login(event) {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
client.invoke("login", username, password, function(error, res, more) {
if (res){
notifier.notify({"title" : "Radiam", "message" : res});
}
});
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("login").addEventListener("click", login(event));
})
Am I missing something? Again, not a js person (I'm building a GUI to a Python script, which is otherwise working great), but it seems like it should be obvious...
Thanks!
This worked. I think it was the wrong type of listener, plus I shouldn't have been trying to pass event:
const notifier = require("node-notifier");
const zerorpc = require("zerorpc");
let client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
function login() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
client.invoke("login", username, password, function(error, res, more) {
if (res){
notifier.notify({"title" : "Radiam", "message" : res});
}
});
}
document.getElementById("login").addEventListener("click", login);

Javascript variables braces html tag not interpreted

I have a problem with the outlook API. I display mails but the body doesn't interpret html tags. I only see the source code of the page.I tried a lot of things but I can't get the tags interpreted. Anybody got a solution? Thank you
// Get the 10 newest messages
client
.api('/me/mailfolders/inbox/messages')
.header('X-AnchorMailbox', emailAddress)
.top(1)
.select('subject,from,receivedDateTime,bodyPreview,uniqueBody')
.orderby('receivedDateTime DESC')
.get((err, res) => {
if (err) {
callback(null, err);
} else {
callback(res.value);
}
});
} else {
var error = { responseText: 'Could not retrieve access token' };
callback(null, error);
}
});
<div class="test">
<!-- Handlebars template for message list -->
<script id="msg-list-template">
<div class="row">
<div class="col-lg-6">
{{#each messages}}
<div class="list-group-item">
<h3 id="msg-from" class="">{{this.from.emailAddress.name}}</h3>
<h4 id="msg-subject" class="list-group-item-heading">{{this.subject}}</h4>
<p id="msg-received" class="list-group-item-heading text-muted"><em>Received: {{formatDate this.receivedDateTime}}</em></p>
<p id="msg-bodyPreview" class="list-group-item-text text-muted azerty"><em>{{this.bodyPreview}}</em></p>
<p id="msg" class=""><em>{{this.uniqueBody.content}}</em></p>;
</div>
{{/each}}

How to display individual blog post by its ID in Angular/Express/MongoDB app

I can't figure out how to get a single blog post by its ID -- I'm very new to this.
So far my main blog app has an ng-repeat which can get all posts. What I want is to be able to click on the name of the post and be show only that post and nothing else -- eventually I want to be able to delete and edit by ID as well.
I know filters exist, but I am not sure how to have a filter enabled by clicking, or how to make sure that when I click it, it will filter by that _id.
My 'post.html' looks as follows -
<div ng-controller="PostController" class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<strong>
<a href ng-click="selectTab('viewPost')">{{post.title}}</a>
</strong> created on {{post.time | date: 'MM/dd/yy # h:mma'}}
</h3>
</div>
<div class="panel-body">
{{post.body}} <br>
{{post._id}}
</div>
</div>
At the moment I have the ng-click directive set up to show this-
<div ng-show="isSelected('viewPost')">
<view-post></view-post>
</div>
Which is a custom directive linking this file --
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<strong>
<a href>{{postById.title}}</a>
</strong> created on {{postById.time | date: 'MM/dd/yy # h:mma'}}
</h3>
</div>
<div class="panel-body">
{{postById.body}}
</div>
</div>
When that template is shown, the expressions are missing altogether.
I have a getPost function in my controller 'PostController' but I'm not sure how to use it.
$scope.getPost = function () {
$http({method: 'GET', url: '/api/blog/:post_id', data: $scope.postById})
.then(function(response){
//your code in case the post succeeds
console.log(response);
})
.catch(function(err){
//your code in case your post fails
console.log(err);
});
}
My API works using Postman, as I can get/update/delete posts on that route. At the moment I have nothing going on in the address bar, no routes in particular -- everything is based around custom directives displaying the templates I want when clicked.
I had thought it could be a problem with the scope of my controllers.
A snippet of my HTML might make it more apparent--
<body ng-controller="PanelController">
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<nav-bar></nav-bar>
</div>
<div ng-controller="PostController">
<div ng-show="isSelected('blog')">
<div ng-repeat="post in posts | orderBy: 'time':true">
<blog-post></blog-post>
</div>
</div>
<div ng-show="isSelected('about')">
<about-page></about-page>
</div>
<div ng-show="isSelected('contact')">
<contact></contact>
</div>
<div ng-show="isSelected('createPost')">
<create-post></create-post>
</div>
<div ng-show="isSelected('viewPost')">
<view-post></view-post>
</div>
</div>
</div>
Hopefully this makes some sense to someone. Any help is appreciated.
EDIT: Just to make it a bit more complete, here's the API for getting posts by ID -
router.route('/blog/:post_id')
.get(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err) {
res.send(err);
} else {
res.json(post);
}
});
})
.put(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err) {
res.send(err);
} else {
post.title = req.body.title;
post.body = req.body.body;
}
post.save(function(err) {
if (err) {
res.send(err);
} else {
res.json({ message: 'Post updated!' });
}
});
});
})
.delete(function(req, res) {
Post.remove({
_id: req.params.post_id
}, function(err, post) {
if (err) {
res.send(err);
} else {
res.json({ message: 'Successfully deleted' });
}
});
});
You need to assign your response data to $scope.post It would look something like this...
$http(...).then(function(response) {
$scope.post = response.post;
});

Categories