ios 403 错误 - 这是一个错误。错误:disallowed_useragent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40591090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
403 Error - Thats an error. Error: disallowed_useragent
提问by Subbu
I am trying to authorise a user for Google calendar API inside an IOS app. I am using the OAuth2 feature of Google to authenticate users. Authorisation page opens with a 403 error with the description:
我正在尝试授权用户使用 IOS 应用程序中的 Google 日历 API。我正在使用 Google 的 OAuth2 功能对用户进行身份验证。授权页面打开时出现 403 错误,说明如下:
This user-agent is not permitted to make OAuth authorisation request to Google as it is classified as an embedded user-agent (also known as a web-view). Per our policy, only browsers are permitted to make authorisation requests to Google. We offer several libraries and samples for native apps to perform authorisation request in browser.
此用户代理不允许向 Google 发出 OAuth 授权请求,因为它被归类为嵌入式用户代理(也称为网络视图)。根据我们的政策,只有浏览器才能向 Google 发出授权请求。我们为原生应用程序提供了多个库和示例,以在浏览器中执行授权请求。
I followed the same procedure which is mentioned in this link: https://developers.google.com/google-apps/calendar/quickstart/ios
我遵循了此链接中提到的相同程序:https: //developers.google.com/google-apps/calendar/quickstart/ios
Rather than seeing my code, it's better to look at this link: https://developers.google.com/google-apps/calendar/quickstart/iosbecause I copy-pasted the same thing in my application.
与其查看我的代码,不如查看此链接:https: //developers.google.com/google-apps/calendar/quickstart/ios,因为我在我的应用程序中复制粘贴了相同的内容。
below are my clientId and keyChainItemName:
下面是我的 clientId 和 keyChainItemName:
static NSString *const kKeychainItemName = @"Google Calendar API";
static NSString *const kClientID = @"954370342601-sgl8k0jrbqdeagea9v6vfu3tspte96ci.apps.googleusercontent.com";
回答by Dipen Chudasama
In my case I was using native web view to login with Google, I find out the way that you should provide user agent to webview it was worked for me. Try below code I am sure it will worked.
就我而言,我使用本机 Web 视图登录 Google,我发现您应该向 Web 视图提供用户代理的方式对我有用。试试下面的代码,我相信它会起作用。
Add the code in application didFinishLaunchingWithOptions
在应用程序 didFinishLaunchingWithOptions 中添加代码
Objective C
目标 C
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
Swift 3.0
斯威夫特 3.0
let dictionary = NSDictionary(object: "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", forKey: "UserAgent" as NSCopying)
UserDefaults.standard.register(defaults: dictionary)
回答by Hardeep Singh
<preference name="OverrideUserAgent" value="Mozilla/5.0 Google" />
I also face this issue on my cordova project. You can try this: Just add this to your config.xml, worked for me.
我的cordova项目也面临这个问题。你可以试试这个:只需将它添加到你的 config.xml 中,对我有用。
回答by Rhishikeshj
The short answer is that Google has updated its security restrictions for OAuth flow. They are not going to allow native web-views to initiate OAuth flows, but rather are encouraging people to use the OS browsers to do so. In your case, you'll probably have to wait for the Google calendar SDK to update their code to obey the newly recommended flow. More information is available in the Google blog
简短的回答是 Google 已经更新了 OAuth 流程的安全限制。他们不会允许原生 Web 视图启动 OAuth 流程,而是鼓励人们使用操作系统浏览器来这样做。在您的情况下,您可能需要等待 Google 日历 SDK 更新其代码以遵守新推荐的流程。Google 博客中提供了更多信息
EDIT : I have tried to create a cross platform plugin which wraps around the native Google sign-in SDKs for using in a Xamarin forms app. More information can be found here
编辑:我尝试创建一个跨平台插件,该插件包含用于在 Xamarin 表单应用程序中使用的本机 Google 登录 SDK。更多信息可以在这里找到
回答by Maxim Pavlov
As mentioned in previous answers, SFSafariViewController
is a way to go, but for those who still uses WKWebView
for OAuth authorization there is a simple workaround.
正如前面的答案中提到的,SFSafariViewController
是一种方法,但对于那些仍然使用WKWebView
OAuth 授权的人来说,有一个简单的解决方法。
Just change customUserAgent
to either one from listor set it to some arbitrary value. After that disallowed_useragent
error will disappear:
只需更改customUserAgent
为列表中的任一个或将其设置为某个任意值。该disallowed_useragent
错误将消失后:
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
// Check for selector availability, as it is available only on iOS 9+
if ([webView respondsToSelector:@selector(setCustomUserAgent:)]) {
webView.customUserAgent = @"MyCustomUserAgent";
}
For changing User-Agent
in UIWebView
you can check this answer.
对于更改User-Agent
,UIWebView
您可以查看此答案。
But be careful, as some backend code can depend on User-Agent
header value.
但要小心,因为某些后端代码可能依赖于User-Agent
标头值。
回答by Kundan Singh Thakur
Got same issue. Resolvedby setting following property to the webview object:
有同样的问题。通过将以下属性设置为 webview 对象来解决:
webview.getSettings().setUserAgentString("Chrome/56.0.0.0 Mobile");
Hope this will help.
希望这会有所帮助。
回答by Ramaraj T
By default, if you don't have any google app, the google SDK opens the login inside a UIWebView
when we initiate the login by using the following method.
默认情况下,如果您没有任何谷歌应用程序,UIWebView
当我们使用以下方法启动登录时,谷歌 SDK 会在 a 内打开登录。
[[GIDSignIn sharedInstance] signIn];
I just added one line before this, which is as follows.
在这之前我只是添加了一行,如下所示。
[[GIDSignIn sharedInstance] setAllowsSignInWithWebView:NO];
Now the google doesn't authorise using the UIWebView
popup. Instead, it opens in the Safari browser. And now everything just works as the way it was.
现在谷歌不授权使用UIWebView
弹出窗口。相反,它会在 Safari 浏览器中打开。现在一切都照原样运行。
回答by Tmm
Google decided to not longer allow embedded browsers to handle the oAuth authentication. The best way is to use SFSafariViewController on iOS. Here is how it can be solved using the CloudRail SDK:
Google 决定不再允许嵌入式浏览器处理 oAuth 身份验证。最好的方法是在 iOS 上使用 SFSafariViewController。以下是使用 CloudRail SDK 解决此问题的方法:
In Objective-C:
在 Objective-C 中:
@implementation AppDelegate
// This method will receive the redirect URI after the authentication process was
// successfull
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
// Here we pass the response to the SDK which will automatically
// complete the authentication process.
[[NSNotificationCenter defaultCenter] postNotificationName:@"kCloseSafariViewControllerNotification" object:url];
return YES;
}
@end
and Swift:
和斯威夫特:
// This method will receive the redirect URI after the authentication process was
// successfull
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if (sourceApplication == "com.apple.SafariViewService") {
// Here we pass the response to the SDK which will automatically
// complete the authentication process.
NSNotificationCenter.defaultCenter().postNotificationName("kCloseSafariViewControllerNotification", object: url)
return true
}
return true
}
The complete blog post covering this issue can be found here: Solving ‘disallowed_useragent' for Google services
可以在此处找到涵盖此问题的完整博客文章:Solving 'disallowed_useragent' for Google services
回答by Jen Jose
There is a workaround for this issue after the recent change in Google OAuth policies.
在最近更改 Google OAuth 策略后,此问题有一个解决方法。
After integrating the Google Sign and enabling Google Calendar API, I was able to work with Google Calendar API to fetch and add Calendar Events. We just have to set the authorizer for GTLServiceCalendar which is obtained after Google sign-in.
在集成 Google Sign 并启用 Google Calendar API 后,我能够使用 Google Calendar API 来获取和添加日历事件。我们只需要为谷歌登录后获取的 GTLServiceCalendar 设置授权者。
service.authorizer = user.authentication.fetcherAuthorizer()
service.authorizer = user.authentication.fetcherAuthorizer()
Here is the code snippets of Google GIDSignIn, followed by fetching calendar events.
这是 Google GIDSignIn 的代码片段,然后是获取日历事件。
import GoogleAPIClient
import GTMOAuth2
import UIKit
import GoogleSignIn
class ViewController: UIViewController, GIDSignInUIDelegate, GIDSignInDelegate {
private let kApiKey = "AIzaXXXXXXXXXXXXXXXXXXXXXXX"
// If modifying these scopes, delete your previously saved credentials by
// resetting the iOS simulator or uninstall the app.
private let scopes = [kGTLAuthScopeCalendar]
private let service = GTLServiceCalendar()
override func viewDidLoad() {
super.viewDidLoad()
service.apiKey = kApiKey
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().scopes = scopes
GIDSignIn.sharedInstance().signIn()
GIDSignIn.sharedInstance().delegate = self
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if user != nil {
print("\(user)")
service.authorizer = user.authentication.fetcherAuthorizer()
fetchEvents()
}
}
// Construct a query and get a list of upcoming events from the user calendar
func fetchEvents() {
let query = GTLQueryCalendar.queryForEventsList(withCalendarId: "primary")
query?.maxResults = 20
query?.singleEvents = true
query?.orderBy = kGTLCalendarOrderByStartTime
service.executeQuery(query!, delegate: self, didFinish: #selector(ViewController.displayResultWithTicket(ticket:finishedWithObject:error:)))
}
// Display the start dates and event summaries in the UITextView
func displayResultWithTicket(
ticket: GTLServiceTicket,
finishedWithObject response : GTLCalendarEvents,
error : NSError?) {
if let error = error {
showAlert(title: "Error", message: error.localizedDescription)
return
}
var eventString = ""
if let events = response.items(), !events.isEmpty {
for event in events as! [GTLCalendarEvent] {
print(event)
}
} else
print("No upcoming events found.")
}
}
}
This is how my credentials section appear in Google Dev Console.
这就是我的凭据部分在 Google Dev Console 中的显示方式。
回答by Sally
Take a look at this issue.Use GTMAppAuth instead.
看看这个问题。请改用 GTMAppAuth。
回答by dev_mg99
This is working for me
这对我有用
mWebView.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19");