Background:
I'm upgrading my app to use WKWebview from UIWebview as it will no longer be accepted by App Store
The App Store will no longer accept new apps using UIWebView as of April 2020 and app updates using UIWebView as of December 2020.
Issue:
What happen is, I'm getting cookie return from Webview (WKWebview) after logged in. I will retrieve a token I need for API firing, however I'm constantly hitting HTTP 401 status for all the API(s) fired.
If I revert back to UIWebview, and repeat the same for login but re-using the SAME TOKEN from WKWebview. I'm getting HTTP 200 status. Purpose of re-using same token is to prove that is a valid token.
Noted that, I have not make any changes to the method calling API. It remains the same for both WKWebview and UIWebview. (Including the object request for POST method)
Am I missing something in WKWebview?
Do I need to set cookie or allow anything in specific?
Code snippet:
<WebView
style={{ width: this.state.webviewWidth }}
ref={(component) => {
this.webviewRef = component;
}}
source={{ uri: this.state.url }}
onLoadStart={this.webviewOnLoadStart}
onLoad={this.webviewOnLoadEnd}
onNavigationStateChange={this.onNavigationStateChange}
useWebKit={true}
sharedCookiesEnabled={true}
/>
Pacakge.json
"react-native": "0.61.5",
"react-native-webview": "^10.3.2",
"#react-native-community/cookies": "^3.0.0",
Apparently the issue is that WKWebview does not handle cookie passing into the request header for us. Hence I received 401 authentication failure every time when I reach the server.
Unfortunately React-Native-Webview does not has a way to handle this cookie header passing out of the box (Please correct me if I'm wrong). I'm fully aware of this 'custom header' function provided within the lib, unfortunately it didn't work as expected. The cookie is still not part of the request header.
My solution to this is as follow, did under method decidePolicyForNavigationAction:
Dive into native lib (React-Native-Webview)
Loop through all existing cookies within websiteDataStore.httpCookieStore
Look for my cookie (of course, you should know your cookie name)
Append the cookie into the HTTPHeaderField to your http request
Load the http request again!
if (#available(iOS 11.0, *)) {
[webView.configuration.websiteDataStore.httpCookieStore getAllCookies:^(NSArray<NSHTTPCookie *> * _Nonnull cookies) {
NSLog(#"All cookies in websiteDataStore %#", cookies);
for(NSHTTPCookie *cookie in cookies){
if([cookie.name isEqualToString:#"coookieName"]){
if([navigationAction.request valueForHTTPHeaderField:#"Cookie"] != nil ){
}else{
NSMutableURLRequest *req = [request mutableCopy];
NSString *newCookie = [NSString stringWithFormat:#"cookieName=%#" , cookie.value];
// As you can see, I'm appending the cookie value into header myself
[req addValue:newCookie forHTTPHeaderField:#"Cookie"];
[req setHTTPShouldHandleCookies:YES];
[webView loadRequest:req];
return;
}
}
}
}];
} else {
// Fallback on earlier versions
}
Related
I have a simple WKWebView in macOS. I'm facing issues with redirection when visiting a page without www that then redirects to the subdomain www.
As far as I could find out I'd simply have to allow the navigation request and the webView should handle everything itself. But the redirect never actually happens. The webView ends up in a redirect loop, calling didReceiveServerRedirectForProvisionalNavigation: over and over again until finally failing with Error Domain=NSURLErrorDomain Code=-1007 "too many HTTP redirects"
Safari, other browsers and clients do indeed succeed, what makes me believe that it's not a server issue.
Also when I enter the address redirected to directly, it does work without any issues.
I implemented the WKNavigationDelegate protocol as follows:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if ([navigationAction navigationType] == WKNavigationTypeOther) {
if ([[[[navigationAction request] URL] host] isEqualToString:[[[self webView] URL] host]]) {
decisionHandler(WKNavigationActionPolicyAllow);
NSLog(#"allowed");
return;
}
decisionHandler(WKNavigationActionPolicyCancel);
NSLog(#"cancelled: %#", [navigationAction request]);
}
else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(#"provisional navigation started");
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation; {
NSLog(#"provisional navigation received redirect");
}
I'm expecting the webView to accept and actually follow the redirect after I answered using WKNavigationActionPolicyAllow.
When I execute a request the following happens:
decidePolicyForNavigationAction: for main domain name
I respond with allow
didStartProvisionalNavigation:
decidePolicyForNavigationAction: for redirect with subdomain
I respond with allow
didReceiveServerRedirectForProvisionalNavigation:
Back to 6.
Do I have to somehow "commit" the redirect or do it manually myself?
Any ideas or did I miss something completely?
Stupid me. Really. Embarrassingly stupid.
My table now has my face embossed.
My original code was cut down for overview until a point where I deleted my issue...
I'm working on a special use case where the host name is not in the URL. I connect to a multi-site web server via it's IP and set the Host header accordingly to get the desired page.
When redirected I copy the request, set the header accordingly and resend the request. Guess what? Responding to a redirect by sending the same Host: header will result in another redirect. Grr.
I'll leave this here for public amusement to a day or two
I'm creating a small forum where people in our company can put up adverts for goods or services they want to sell on the fly, using aurelia. I have a list of adverts page working fine, a details page for each advert working fine both using get requests from an api. However i can't seem to get the work the Post reqeust when someone wants to add a comment on an advert.
#inject(HttpClient)
export class ApiData {
constructor(httpClient) {
httpClient.configure(config => {
config
.withBaseUrl("MyUrl");
});
this.http = httpClient;
//.configure(x => {x.withHeader('Content-Type', 'application/json');});
}
postAdvertComment(comment, id) {
return this.http.fetch(`/adverts/${id}/comments`, {
method: "post",
body: json(comment),
headers: {
'Accept': 'application/json'
}
});
}
getAdverts() {
return this.http.fetch("/adverts")
.then(response => {
return this.adverts = response.json();
});
}
getAdvert(id) {
return this.http.fetch(`/adverts/${id}`)
.then(response => {
return this.advert = response.json();
});
}
}
Doing this project we've had some issue with CORS, all solved by adding in AllowCors tags in the api, including all methods etc.
<add key="CorsAllowedOrigins" value="*" />
<add key="CorsAllowedHeaders" value="" />
<add key="CorsAllowedMethods" value="*" />
However when i try and run the post, its running an options method and returns a 400 Bad request.
Here
We also get the following CORS error:
Fetch API cannot load MyURL/api/adverts/2/comments. Response to preflight
request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://localhost:49877' is
therefore not allowed access. The response had HTTP status code 400. If an
opaque response serves your needs, set the request's mode to 'no-cors' to fetch
the resource with CORS disabled.
I don't know if it's a problem with our c# api or with how I'm trying to post from aurelia, but we have tried sending requests from postman and it works fine, tried sending post request within the same app using jquery and it works fine, and all the get requests work fine, but for some reason this post is causing all sorts of problems.
It seems to be a problem in your WebAPI, but before giving you some possible solutions I'd like to show you some important things.
Postman is not affected by CORS, so all requests work.
jQuery ajax uses XHR (XmlHttpRequest object) while aurelia-fetch-client uses fetch (window.fetch. However, the fetch-polyfill uses XHR in the background). They are
different approaches to solve the same problem. Just because one of them work, doesn't actually mean that the other one should work too.
The OPTIONS request is made by fetch, that's how it works. More information here https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en
To solve this problem try to remove those tags from web.config, and allow CORS in your Startup.cs. Like this:
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll); //or another parameter
//rest of your code
}
You don't have to set the content-type header to application/json. It is automatically made when you use the json() function ---> body: json(comment)
If you are using OWIN you might have to send the content-type as x-www-form-urlenconded. In that case, take a look at this Post 'x-www-form-urlencoded' content with aurelia-fetch-client
My app uses OneDrive API feature to let unauthorized users get thumbnails for shared OneDrive files using old API request:
https:// apis.live.net/v5.0/skydrive/get_item_preview?type=normal&url=[shared_link_to_OneDrive_file]
This feature is broken now (any such links return XMLHttpRequest connection error 0x2eff).
And my Windows Store app can not longer provide this feature.
Anyone can try to check it, link to shared OneDrive file:
https://onedrive.live.com/redir?resid=AABF0E8064900F8D!27202&authkey=!AJTeSCuaHMc45eY&v=3&ithint=photo%2cjpg
links to a preview image for shared OneDrive file (according to old OneDrive API
"Displaying a preview of a OneDrive item" - https:// msdn.microsoft.com/en-us/library/jj680723.aspx):
https://apis.live.net/v5.0/skydrive/get_item_preview?type=normal&url=https%3A%2F%2Fonedrive.live.com%2Fredir%3Fresid%3DAABF0E8064900F8D!27202%26authkey%3D!AJTeSCuaHMc45eY%26v%3D3%26ithint%3Dphoto%252cjpg
generates error: SCRIPT7002: XMLHttpRequest: Network error 0x2eff
Сurrent OneDrive API thumbnail feature:
GET /drive/items/{item-id}/thumbnails/{thumb-id}/{size}
is just for authorized users and can not provide access to thumbnails for shared OneDrive files to unauthorized users
How can a Windows Store app let unauthorized users get thumbnails for shared OneDrive files (videos etc.) using the current OneDrive API?
Any ideas?
You need to make a call to the following API:
GET /drive/items/{item-id}/thumbnails/{thumb-id}/{size}/content
This call needs to use authorization and returns a redirect to a cache-safe thumbnail location. You can then use this new url to serve thumbnails to unauthenticated users.
e.g.
Request:
GET https://api.onedrive.com/v1.0/drive/items/D094522DE0B10F6D!152/thumbnails/0/small/content
Authorization: bearer <access token>
Response:
HTTP/1.1 302 Found
Location: https://qg3u2w.bn1302.livefilestore.com/y3m1LKnRaQvGEEhv_GU3mVsewg_-aizIXDaVczGwGFIqtNcVSCihLo7s2mNdUrKicuBnB2sGlSwMQTzQw7v34cHLkchKHL_5YC3IMx1SMcpndtdb9bmQ6y2iG4id0HHgCUlgctvYsDrE24XALwXv2KWRUwCCvDJC4hlkqYgnwGBUSQ
You can now use the link in the Location header to access the thumbnail without signing in. This url will change only if the contents of the file change.
You can read more in the documentation here.
I just figured it out. It is based on the information in this article from Microsoft...
https://learn.microsoft.com/en-ca/onedrive/developer/rest-api/api/driveitem_list_thumbnails?view=odsp-graph-online
... look at the section, "Getting thumbnails while listing DriveItems." It shows you the relevant JSON return structure from a call such as:
GET /me/drive/items/{item-id}/children?$expand=thumbnails
Basically, the JSON return structure gives you string URL's for each of the thumbnail formats. You then create URLSession's to upload these URL's (once you've converted them from String to URL)
Here is an excerpt of code using Swift (Apple):
////////////////////////////////////////////////////////////////////////////////
//
// Download a thumbnail with a URL and label the URLSession with an ID.
//
func downloadThumbnail(url: URL, id: String) {
// Create a URLSession. This is an object that controls the operation or flow
// control with respect to asynchronous operations. It sets the callback delegate
// when the operation is complete.
let urlSession: URLSession = {
//let config = URLSessionConfiguration.default
let config = URLSessionConfiguration.background(withIdentifier: id)
config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
//config.identifier = "file download"
return URLSession(configuration: config, delegate: self as URLSessionDelegate, delegateQueue: OperationQueue.main)
}()
// Create the URLRequest. This is needed so that "Authorization" can be made, as well
// as the actual HTTP command. The url, on initialization, is the command... along
// with the "GET" setting of the httpMethod property.
var request = URLRequest(url: url)
// Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result
request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// This initiates the asynchronous data task
let backgroundTask = urlSession.downloadTask(with: request)
//backgroundTask.earliestBeginDate = Date().addingTimeInterval(60 * 60)
backgroundTask.countOfBytesClientExpectsToSend = 60
backgroundTask.countOfBytesClientExpectsToReceive = 15 * 1024
backgroundTask.resume()
}
... of course you need to have the correct "accessToken," (shown above) but you also have to have written the generic callback function for URLSession, which is:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
Swift.print("DEBUG: urlSession callback reached")
// This was the identifier that you setup URLSession with
let id = session.configuration.identifier
// "location" is the temporary URL that the thumbnail was downloaded to
let temp = location
// You can convert this URL into any kind of image object. Just Google it!
}
Cheers, Andreas
I'm trying to use the implicit authentication of the StackExchange API, and therefor I need to send the user to https://www.stackexchange.com/oauth?client_id=...&scope=...&redirect_uri=... (with actual values instead of '...'). Easy, just drag out a WebView in Interface Builder and implement -webView:didFinishLoadForFrame: from the WebFrameLoadDelegate protocol to track if we are at the redirect_uri already. That works exactly as I want it to. But the WebView internals don't. An error page from stackexchange.com/oauth:
Application Login Failure
An error occurred while login into an application.
Error Details:
error: invalid_request
error description: OAuth request must be over HTTPS
But I started the URL with https://:
- (void)awakeFromNib {
NSString *oauthAddress = #"https://www.stackexchange.com/oauth?client_id=...&scope=...&redirect_uri=...";
[loginWebView setMainFrameURL:oauthAddress];
}
I can't find any source that says you have to do something else to enable HTTPS on a standard WebView.
It is caused by the WebView internals: in -webView:didFinishLoadForFrame: I NSLog()' the current URL:
- (void)webView:(WebView *)webView didFinishLoadForFrame:(WebFrame *)webFrame {
NSString *currentURL = [[[[webFrame dataSource] request] URL] absoluteString];
NSLog(#"-webView:didStartProvisionalLoadForFrame:");
NSLog(#"Current URL: %#", currentURL);
if ([currentURL hasPrefix:#"https://stackexchange.com/oauth/login_success"]) {
NSLog(#"We did login!");
}
}
Output:
2013-03-05 15:31:55.493 MacOverflow[2164:a0f] -webView:didStartProvisionalLoadForFrame:
2013-03-05 15:31:55.495 MacOverflow[2164:a0f] Current URL: http://stackexchange.com/oauth?client_id=...scope=...&redirect_uri=...
What the?! WebKit removed the 's' from the protocol part of the URL! How to stop WebKit from doing so? I searched Apple's documentation on WebView (with Cmd+f) for 'https' (0 matches), 'ssl' (0 matches) and even 'secure' (again 0 matches). I'm kinda stuck here, but it must be possible. It would be ridiculous to provide such a sophisticated browser control, but force the developer to write a copy for supporting https (which is quite common nowadays IMO)!
How to make an HTTPS request using WebKit's WebView?
This is not related to WebKit.
Remove www. from your URL like so https://stackexchange.com/oauth and you should be fine. At least that works for me.
I have to integrate linkedIn sharing in my app, I will be using this framework.
It has a sample project. I open it, set up my apikey and secret key but the authorisation doesn't happen. Login window is opened and immediately closed,when I click get linkedIn profile. Also when I set up my linkedIn app, what should I put into JavaScript API domain? Now I put:
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: myapikey
authorize: true
</script>
- (void)initLinkedInApi
{
apikey = #"myapikeys";
secretkey = #"mysecretkey";
self.consumer = [[OAConsumer alloc] initWithKey:apikey
secret:secretkey
realm:#"http://api.linkedin.com/"];
requestTokenURLString = #"https://api.linkedin.com/uas/oauth/requestToken";
accessTokenURLString = #"https://api.linkedin.com/uas/oauth/accessToken";
userLoginURLString = #"https://www.linkedin.com/uas/oauth/authorize";
linkedInCallbackURL = #"hdlinked://linkedin/oauth";
requestTokenURL = [[NSURL URLWithString:requestTokenURLString] retain];
accessTokenURL = [[NSURL URLWithString:accessTokenURLString] retain];
userLoginURL = [[NSURL URLWithString:userLoginURLString] retain];
}
And also I get this error:
Unbalanced calls to begin/end appearance transitions for .
You shouldn't need to put any javascript in the file at all. The sample client (I just checked to make sure it works in the latest XCode and with IOS5. All you need to do is put in your key and secret and it should just run in the simulator and on a dev device.
Why are you adding javascript into the code?