GTM OAuth для IOS не работает с поставщиком Grails OAuth 2
В настоящее время я работаю над приложением IOS и хочу использовать OAuth для аутентификации этого приложения с помощью имеющейся у нас системы Grails. Система grails имеет настройку поставщика OAuth2 с помощью плагина по ссылке ниже:
https://github.com/adaptivecomputing/grails-spring-security-oauth2-provider
Поставщик OAuth настроен, и он работает, так как я проверил URL-адреса, показанные ниже, и получаю код авторизации, как и ожидалось, после предоставления доступа:
http://localhost:8080/app/oauth/authorize?response_type=code&client_id=clientId&redirect_uri=http://localhost:8080/app/
У меня проблема в том, что когда я использую плагин GTM OAuth для IOS от Google, я настроил его следующим образом:
static NSString *const kMyClientID = @"1";
static NSString *const kMyClientSecret = @"secret";
static NSString *const kKeychainItemName = @"systemKeychain";
- (GTMOAuth2Authentication *)systemAuth
{
// Set the token URL to the system token endpoint.
NSURL *tokenURL = [NSURL URLWithString:@"http://www.systemurl.co.uk/oauth/token"];
// Set a bogus redirect URI. It won't actually be used as the redirect will
// be intercepted by the OAuth library and handled in the app.
NSString *redirectURI = @"http://www.systemurl.co.uk/";
GTMOAuth2Authentication *auth;
auth = [GTMOAuth2Authentication authenticationWithServiceProvider:@"SYSTEM API"
tokenURL:tokenURL
redirectURI:redirectURI
clientID:kMyClientID
clientSecret:kMyClientSecret];
return auth;
}
- (void)authorize:(NSString *)service
{
GTMOAuth2Authentication *auth = [self systemAuth];
// Prepare the Authorization URL. We will pass in the name of the service
// that we wish to authorize with.
NSURL *authURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.systemurl.co.uk/oauth/authorize"]];
// Display the authentication view
GTMOAuth2ViewControllerTouch *viewController;
viewController = [ [GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:auth
authorizationURL:authURL
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:@selector(viewController:finishedWithAuth:error:)];
[viewController setBrowserCookiesURL:[NSURL URLWithString:@"http://www.systemurl.co.uk/"]];
// Push the authentication view to our navigation controller instance
[ [self navigationController] pushViewController:viewController animated:YES];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error
{
if (error != nil)
{
// Authentication failed
UIAlertView *alertView = [ [UIAlertView alloc] initWithTitle:@"Authorization Failed"
message:[error localizedDescription]
delegate:self
cancelButtonTitle:@"Dismiss"
otherButtonTitles:nil];
[alertView show];
}
else
{
// Authentication succeeded
// Assign the access token to the instance property for later use
self.accessToken = auth.accessToken;
// Display the access token to the user
UIAlertView *alertView = [ [UIAlertView alloc] initWithTitle:@"Authorization Succeeded"
message:[NSString stringWithFormat:@"Access Token: %@", auth.accessToken]
delegate:self
cancelButtonTitle:@"Dismiss"
otherButtonTitles:nil];
[alertView show];
}
}
Проблема в том, что когда я запускаю приведенный выше код, он перенаправляет меня в систему, и я вхожу в систему, затем появляется страница, чтобы я мог предоставить доступ к этому приложению, и я нажимаю "Авторизовать", и приложение показывает мне представление с предупреждением ошибка 500 в этом.
Поэтому я вернулся к системе Grails и посмотрел журналы, чтобы увидеть, что произошло, и заметил, что приложение передало URL-адрес:
"GET /oauth/authorize?client_id=1&redirect_uri=http%3A%2F%2Fwww.systemurl.co.uk%2F&response_type=code HTTP/1.1" 302 -
"GET /oauth/authorize?client_id=1&redirect_uri=http%3A%2F%2Fwww.systemurl.co.uk%2F&response_type=code HTTP/1.1" 200 6923
"POST /oauth/authorize?client_id=1&redirect_uri=http%3A%2F%2Fwww.systemurl.co.uk%2F&response_type=code HTTP/1.1" 302 -
и сообщение об ошибке 500 показано ниже из системы:
2014-03-24 08:25:53,081 [http-8080-2] ERROR errors.GrailsExceptionResolver - NoSuchClientException occurred when processing request: [POST] /oauth/token - parameters:
client_secret: secret
grant_type: authorization_code
redirect_uri: http://www.systemurl.co.uk/
code: 4bf5Se
client_id: 1
No client with requested id: testing. Stacktrace follows:
org.springframework.security.oauth2.provider.NoSuchClientException: No client with requested id: testing
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:179)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.java:53)
at grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:49)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:82)
at java.lang.Thread.run(Thread.java:722)
Теперь приведенная выше ошибка подсказывает мне, что по какой-то причине имя пользователя каким-то образом используется в качестве идентификатора клиента, и я не знаю почему, так как имя пользователя и пароль "тестируются" в системе grails.
Может ли кто-нибудь предложить какие-либо советы о том, почему это может происходить?
заранее спасибо
*** РЕДАКТИРОВАТЬ * ****
Я отладил отправляемые HTTP-запросы, и ниже приведен RAW-запрос для получения токена:
POST /oauth/token HTTP/1.1
Host: www.systemurl.co.uk
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Accept-Language: en-us
Cookie: JSESSIONID=70EB045C21084E166A34EDA88FE155C8.28151
Accept: */*
Content-Length: 130
Connection: keep-alive
User-Agent: gtm-oauth2 com.test.OAuthGTM/1.0
client_id=1&client_secret=secret&code=VaYn8M&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fwww.systemurl.co.uk%2F
1 ответ
Краткий ответ: "client_id=public", тогда это работает
Длинный ответ:
Если вы отладите код, вы обнаружите, что исключение выдается в InMemoryClientDetailsService.
В Grails версии 2.2.4 код выглядит примерно так
private Map<String, ? extends ClientDetails> clientDetailsStore = new HashMap<String, ClientDetails>();
public ClientDetails loadClientByClientId(String clientId) throws OAuth2Exception {
ClientDetails details = clientDetailsStore.get(clientId);
if (details == null) {
throw new InvalidClientException("Client not found: " + clientId);
}
return details;
}
В Map clientDetailsStore есть только одно значение, которое является "общедоступным"