Token Mismatch issue in IFrame in Internet Explorer. Laravel 5.2 - laravel-5.1

What's the problem ?
I am facing Token Mismatch issue when accessing the site in IFrame in Internet Explorer.
What I tried so far ?
I search for the resolution and found this link
Below is the code that I found in the above link
App::after(function ($request,$response){
if($request->is('external/*')){
// IE iframe cookie fix
$response->header('P3P',
'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
}
});
What's the question ?
Where should I write the above code in Laravel 5.2 ?

You should create after middleware and add this middleware to web middleware assuming you use web group middleware for your routes.
Sample middleware:
<?php
namespace App\Http\Middleware;
use Closure;
class FixIeFrameMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
if($request->is('external/*')){
// IE iframe cookie fix
$response->header('P3P',
'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
}
return $response;
}
}
and now in app/Http/Kernel.php in $middlewareGroups property for web group you should add new array element:
\App\Http\Middleware\FixIeFrameMiddleware::class,

Related

Swashbuckle's OAuth fails when response returned to o2c-html

My super simple sample Web API app is successfully rendering a swagger/ui document. But, it's failing if I try to configure it to do authorized OAuth 2.0 calls.
If you hit the icon to show the OAuth consent prompt, and then hit the Authorize button, I'm successfully redirected to login.microsoftonline.com and am able to successfully supply credentials, but, when I'm redirected back to swagger/ui/o2c-html, it seems that the dynamically generated javascript in that page is buggy...
Generated 'o2c-html' page:
<script>
var qp = null;
if(window.location.hash) {
qp = location.hash.substring(1);
}
else {
qp = location.search.substring(1);
}
qp = qp ? JSON.parse('{"' + qp.replace(/&/g, '","').replace(/=/g,'":"') + '"}',
function(key, value) {
return key===""?value:decodeURIComponent(value) }
):{}
if (window.opener.swaggerUi.tokenUrl)
window.opener.processOAuthCode(qp);
else
window.opener.onOAuthComplete(qp);
window.close();
</script>
When I hover over the qp variable, I can see that I successfully retrieved the desired bearer token, but, as execution proceeds down to the final conditional statements with window.opener everything fails at window.opener.swaggerui
I get the following error:
JavaScript runtime error: Unable to get property 'swaggerUi' of
undefined or null reference occurred
Blockquote
I'm using these NuGet packages, FWIW:
<package id="Swashbuckle" version="5.5.3" targetFramework="net45" />
UPDATE - FIGURED OUT WHAT I DID WRONG
In my case, I did not have the right configuration in SwaggerConfig.cs , in the first section for EnableSwagger(c =>:
I initially had it set like this (don't ask me why):
c.OAuth2("oauth2")
.Description("OAuth2 Implicit Grant")
.Flow("implicit")
.AuthorizationUrl(
string.Format("https://login.microsoftonline.com/{0}/oauth2/authorize",
ConfigurationManager.AppSettings["ida:Tenant"]))
.Scopes(scopes =>
{
scopes.Add("user_impersonation", "Access swagger");
});
But now it all works when I changed it to an exhaustive listing of my actual roles that I use in my controllers...
c.OAuth2("oauth2")
.Description("OAuth2 Implicit Grant")
.Flow("implicit")
.AuthorizationUrl(
string.Format("https://login.microsoftonline.com/{0}/oauth2/authorize",
ConfigurationManager.AppSettings["ida:Tenant"]))
.Scopes(scopes =>
{
scopes.Add("AdminAccess", "Admin access to protected resources");
scopes.Add("FullAccess", "Full access to protected resources");
scopes.Add("UpdateAccess", "Update access to protected resources");
scopes.Add("ReadAcces", "Read access to protected resources");
});
Sorry that is a bug in the Swagger-UI.
Latest version looks different, take a look here: src/main/html/o2c.html
We just have to publish a new NuGet package of Swashbuckle (hopefully soon)

Azure AD B2C OAuth2 how to refresh access token silently

We are using Azure AD B2C to authenticate our users in an ASP.NET MVC application with OWIN (Microsoft.Owin.Security).
We are trying to find a way to refresh silently the access token (access_token), to avoid the multiple AJAX calls we are doing to fail. Most of them are fired automatically by the components we use (DevExpress) through callbacks, so we have very little control over them.
One solution we found is the one described by Vittorio Bertocci on his blog : http://www.cloudidentity.com/blog/2016/07/25/controlling-a-web-apps-session-duration-2/
AccountController.cs
public void ForcedSignIn()
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties {RedirectUri = "/Account/AfterForcedSignIn"}, "OUR_B2C_SIGNIN_POLICY_ID");
}
_Layout.cshtml
<script>
setInterval(function() {
#if (Request.IsAuthenticated)
{
<text>
var renewUrl = "/Account/ForcedSignIn";
var element = document.getElementById("renewSession");
console.log("sending request to: " + renewUrl);
element.src = renewUrl;
</text>
}
},
1000 * 20
);
</script>
<body>
<iframe id="renewSession" style="height: 600px; width: 600px;"></iframe>
AfterForcedSignIn.cshtml
#{
Layout = null;
}
However, the call to https://login.microsoftonline.com is failing because it can’t be embedded in an iFrame (even if we specify “prompt” parameter to “none”).
See the message we get in Edge for example :
Is there a way to avoid this issue (are we missing a parameter when calling the login page, or something else) ? Or is it another solution that exists ?
Thanks,
Léo
If you use MSAL they have an AzquireTokenSilently method that you could use to refresh the user
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet

OAuth 1.0, javascript and server-to-server authentication

We are trying to integrate a "sign in with twitter" function in our application and for this purpose we are using javascript (hello.js).
Unfortunately, twitter is using oauth 1.0 so we can't have only a javascript solution but we need to implement a server-to-server communication to sign the request. The hello.js author provided an auth-server implementation for demo purposes based on node.js.
In our application for the backend part we are using java and I was wondering if a java solution exists for this purpose. Could I use for instance signpost or similar to do the job of auth-server ?
[UPDATE]
I tried to set the proxy used by hello.js to a mine servlet (so, instead of herokuap now I'm using a localhost servlet with oauth in the buildpath).
This servlet is doing the following:
OAuthConsumer consumer = new DefaultOAuthConsumer(
"xxxx",
"yyyyyyyyyyy");
OAuthProvider provider = new DefaultOAuthProvider(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize");
System.out.println("Fetching request token from Twitter...");
// we do not support callbacks, thus pass OOB
String authUrl = provider.retrieveRequestToken(consumer, "http://localhost:8080/oauth1/twitter/response_server");
URL url = new URL(authUrl);
HttpURLConnection req = (HttpURLConnection) url.openConnection();
req.setRequestMethod("GET");
req.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(req.getInputStream()));
StringBuilder d = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null){
d.append(line + '\n');
}
System.out.println(d);
PrintWriter out = response.getWriter();
out.println(d);
and it prints the twitter login page in the hello.js popup. In this way I got some encoding error but it is quite working.
Anyway the callback url is mapped to another servlet where I should simply "sign" the request but I think I am missing something because sometimes I got the error
"The server understand the request but it is still refusing it"
but if I close all browser window it works.
However the response servlet is similar to this one
OAuthConsumer consumer = new AbstractOAuthConsumer(
"xxxxx",
"yyyyyyyyyyy"){
#Override
protected HttpRequest wrap(Object arg0) {
return (HttpRequest)arg0;
}
};
consumer.sign(request);
But this code does not work because I don't know how to sign a tomcat request. In oauth homepage is explained how to sign jetty and apache common http request but not the tomcat one. However, is it correct my approach ?
Please checkout the spec of node-oauth-shim which is used my //auth-server and which HelloJS delivers.

Asp code to Download data from web server?

Can i make asp application or mvc application that can download data from other server (site) using ftp. I have 2 web sites and i want to download a file from one site to another using ftp.
Yes.
Example copied from How to Download Files with FTP. The example is for a console app, but I think you can figure quite easily how to adapt it to your site's structure.
One thing you might consider is just hosting the file on the site (like normal HTTP) and then download it via WebClient instead of FTP.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
}
}
}

Can I call REST web services from Windows Mobile app

I would like to build a simple REST web service (using Ruby on Rails). However, I would like to be able to call this service from a Windows mobile app. Is that possible? or do I have to use SOAP?
I don't have much experience with Windows Mobile apps so it would be nice if you can provide pseudo code or link to tutorial for the possible case.
Thanks,
Tam
Yes you can. I've done it lots using the Win32 wininet API.
You can also do it in C# using the System.Net HttpWebRequest API.
dim sendUrl : sendUrl = baseUrl & url
dim objXML : Set objXML = CreateObject("MSXML2.ServerXMLHTTP.6.0")
objXML.open "GET", sendUrl, false
objXML.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXML.send(sendxml)
HttpPost = objXml.responseText
Set objXML = nothing
On desctop Microsoft offers an com interface which can be used to implement REST APIs.
Maybe this also exists on Windows Mobile.
Here's an example of using a HttpWebRequest to call the twitter search api,hth:
Uri uri = new Uri("http://search.twitter.com/search.json?q=twitter");
String result = String.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}

Resources