Spotify authorization code flow (WPF browser control) C# - c#

I'm using Spotify account service (authorization code flow) to get an authorization code by passing in the required parameters (client_id, response_type and redirect_uri. Its a WPF application so i am using the browser control and navigating the user to
https://accounts.spotify.com/authorize/?client_id=myclientId&response_type=code&redirect_uri=someUri
When i copy paste the link in the browser, i see the right stuff i.e page with the Login to Spotify button but when i am navigating through the browser control in my WPF application, it gives me a file download dialog with Authorize.json file to download with Open and Save options, however in some cases it presents the right page to browser code.
Below is my code:
public winOAuthBrowserForm(string navigateTo)
{
InitializeComponent();
webBrowser.Navigated += webBrowser_Navigated;
webBrowser.Navigate(navigateTo);
}
private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
if(!String.IsNullOrEmpty(e.Uri.Query))
{
//since we are looking for code for authorization that will be exchanged for request token from the server
if (e.Uri.Query.StartsWith("?code=") || e.Uri.Query.Contains("code="))
{
code = HttpUtility.ParseQueryString(e.Uri.Query).Get("code");
this.Close();
}
if (e.Uri.Query.StartsWith("?error=") || e.Uri.Query.Contains("error="))
{
error = HttpUtility.ParseQueryString(e.Uri.Query).Get("error");
this.Close();
}
}
}
And i am calling this control like:
var uri = string.Format(SpotifyAuthUriFormatter, RequestAuthBaseUrl, clientId);
winOAuthBrowserForm form = new winOAuthBrowserForm(uri);
form.ShowDialog();
This is what i see:
UPDATE: When i right click on document and see the properties, i see it changes the URL to something like res://ieframe.dll/navcancl.htm#... I've searched it and found some solutions related to I.E (I'm using latest but you can't be sure that it'll be latest on client machines), some say that its firewall setting. The thing is, it appears sometimes only.
Any ideas? Thanks

Related

Close webview xamarin forms

I have implement payment method with return URL and using webview open URL with my app. Recent, I'am issue want auto close webview with response success or fail process payment.
I encountered this case. Here is the solution I found.
After creating the WebElement, we bind the Navigating event to a certain method.
MyPage.Source = link;
MyPage.Navigating += Webview_Navigating;
MyPage WebElment name.
link is my link address
.
Then we perform our transactions here.
private void Webview_Navigating(object sender, WebNavigatingEventArgs e)
{
var url = e.Url;
if (url.Contains("status=1"))
{
int ordID = 0;
//save order
}
}
For me, if the changed link address checkout status=1, the checkout is successful.
You need to call Url property in WebNavigatingEventArgs to catch the changed url
If useful, choose. Good Luck
Sure! You can get response form WebView.
I recommend you use HybridWebView (see: https://github.com/devsmadeofsteel/Plugin.HybridWebView) as alternative.
Examples:
In Xamarin page, create a browser add register a named callback, and add browser to page childs
HybridWebViewControl Browser = new HybridWebViewControl();
//You can load browser content by string or URL, here is string which you can hard code or store in resource files
Browser.ContentType = Plugin.HybridWebView.Shared.Enumerations.WebViewContentType.Internet;
Browser.Source = YourUrl;
Browser.AddLocalCallback(YourCallBackFunctionName, CallBackFunction);
When run, HybridWebViewControl will insert a function with the name you specified in
YourCallBackFunctionName, and the single parameter is string type. So, In JavaScript of the page loaded by YourUrl, you can call back with the specified CallBackFunctionName:
function AnyFunction() {
//...
YourCallBackFunctionName(YourStringParameter);
}
When you call YourCallBackFunctionName(YourStringParameter) in JavaScript, you can get YourStringParameter in CallBackFunction using C#.
So, you could define different CallBackFunctions or pass different parameters with single CallBackFunction, to control the HybridWebView and the page or view which contain it, such as hide HybridWebView or close the page.
Have a try!

web browser control in winform with google chrome c#

hello all i am creating a winform app in which i am showing a map to all the user but the problem is web browser control is taking ie7 as a default browser and map is not supporting in that particular browser,
error:
You are using a browser that is not supported by the Google Maps
JavaScript API. Consider changing your browser.Learn moreDismiss
i want to open the map from web browser control but not with ie, i want to show with google chrome to get rid of that error,
and i have many administrative rights in my system i can't use registry
is there any ways to do that?
VS default browser control use IE. You should use cefsharp for chrome browser.
First include the library and initialize like this...
public ChromiumWebBrowser browser;
private void InitBrowser()
{
try
{
if (!Cef.IsInitialized)
{
CefSettings settings = new CefSettings();
settings.BrowserSubprocessPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "CefSharp.BrowserSubprocess.exe");
Cef.Initialize(settings);
}
string url = "www.google.com";
browser = new ChromiumWebBrowser(url);
this.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browser.IsBrowserInitializedChanged += browser_IsBrowserInitializedChanged;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void browser_IsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs e)
{
if (((ChromiumWebBrowser)sender).IsBrowserInitialized)
{
//if needed then use dev tool
browser.ShowDevTools();
}
}
For more info please see below link...
https://github.com/cefsharp/CefSharp
https://github.com/cefsharp/CefSharp/wiki/Quick-Start
The Browser component uses the Internet Explorer as engine, so if you want another browser you have to find a component for that.
CefSharp uses chromium as engine.

How to urge a user to update the user's browser when entering a web site

I'm wondering if there is some way to "force" a user to update the user's web browser.
For instance, if a user enters my site and he or she is using an old version of a browser, an area of the page that is ordinarily hidden will be revealed. And that revealed area will contain a browser update recommendation and a hyperlink to an external page where the user can download a new version of the user's browser or update the current version.
Specifically, here are the two aspects of my goal for which I need guidance:
How to recognize the browser and it's version, and
How to show a hidden area specific to the browser the user is currently using. (Maybe there will be an area for each type of common browser, so the question would be how to show the associated area.)
In my research I came across this site which offers a small JavaScript-based notification component:
http://browser-update.org/index.html
This is exactly what I was looking for.
You can for example do this in ActionFilterAttribute. For example it can look like following:
public class WarnAboutOldBrowserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
//check if it browser warning was already checked
if (request.Cookies["checked"] != null)
{
return;
}
//exmaple is for IE 6
if (request.Browser.Browser.Trim().ToUpperInvariant().EqualsExact("IE") && request.Browser.MajorVersion <= 6)
{
filterContext.Controller.ViewData["RequestedUrl"] = request.Url.ToString();
filterContext.Result = new ViewResult { ViewName = "OldBrowserWarning" };
}
//add cookie for caching
filterContext.HttpContext.Response.AppendCookie(new HttpCookie("checked", "true"));
}
}
}
Of course you have to add also a view called "OldBrowserWarning" to display information to user.
Other way is to add warning in _Layout.cshtml and in above code set proper flag in ViewBag

Howto get the RedirectURL from WinRT WebView control

I want to authenticate a windows 8 app via OAuth on a service.
This works by using the WebView control and navigate the user with a proper URL to the service where the authentication takes place.
If the user is authenticated by the service, he is redirected to a success page.
I'd like to get the information about this redirect so that i can start the application automatically.
I've tried the the LoadComplete event which is fired when a page is loaded, but there i only get the request uri, but not the redirect uri.
webView.LoadCompleted += webView_LoadCompleted;
webView.Navigate(new Uri("service uri));
Has anyone an idea howto get the redirect url, or at least the page content(This i could parse and look for something like "great, you're authenticated")
There is a built in mechanism for this that is more secure for users (apps can't snoop passwords). See web authentication broker: http://code.msdn.microsoft.com/windowsapps/Web-Authentication-d0485122
You can get the WebView page content doing something like this:
private void webView_LoadCompleted_1(object sender, NavigationEventArgs e)
{
WebView webView = sender as WebView;
string html = webView.InvokeScript("eval", new string[] {"document.documentElement.outerHTML;"});
// Here you can parse html ....
}
You can use the following method, to redirect up to a URL and then block the further redirection.
WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
var url = args.Uri.ToString();
if(url == "")
args.Cancel = true;
}

Frame Redirect in C#

I would like to execute a frame redirect in C# from my managed module for the IIS 7.
When I call context.Response.Redirect(#"http://www.myRedirect.org");the correct page is shown but also the address is shown in the browser. And that is exactly what I do not want.
So I want something like:
private void OnBeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
// make a frame redirect if a specified page is called
if (context.Request.ServerVariable["HTTP_REFERER"].Equals(#"http://www.myPage.org/1.html"))
{
// perform the frame redirect here, but how?
// so something like
context.Response.Redirect(#"http://www.myRedirect.org");
// but as I said that doesn't redirect as I want it to be
}
}
Any ideas about that?
EDIT:
I tried the example, so I have:
private void OnBeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
// make a frame redirect if a specified page is called
if (context.Request.ServerVariable["HTTP_REFERER"].Equals(#"http://www.myPage.org/1.html"))
{
// perform the frame redirect here, but how?
context.Response.Write(#"<html>");
context.Response.Write(#"<head>");
context.Response.Write(#"</head>");
context.Response.Write(#"<frameset rows=""100%,*"" framespacing=""0"" frameborder=""NO"" border=""0"">");
context.Response.Write(#"<frame src=""http://www.myRedirect.org"" scrolling=""auto"">");
context.Response.Write(#"</frameset>");
context.Response.Write(#"<noframes>");
context.Response.Write(#"<body>Some text...");
context.Response.Write(#"</body>");
context.Response.Write(#"</noframes>");
context.Response.Write(#"</html>");
}
}
But that also doesn't correctly redirect. I still have the redirect address shown in my browser. So any other idea?
EDIT:
I obviously made a mistake. The code above works and does what I want. It first didn't work because my redirect url was doing something unexpected.
To perform a frame redirect you need to send back the HTML code containing a frameset with a single frame, with it's source set to http://www.myRedirect.org. As far as the server and browser is concerned no redirect has happened - it's just received some HTML code.
Performing a Response.Redirect will, as you've observed, cause the browser to make a fresh new request to the new page, showing the user the new address in the title bar. It's typically used for when a page actually changes its address, but the owners still want it reachable from the original URL as well.
EDIT: HTML frame redirect sample: http://en.wikipedia.org/wiki/URL_redirection#Frame_redirects

Categories