0

使用 symfony2、fosuserbundle、fosoauthserverbundle 和 gtm-oauth2,一旦您获得授权令牌,oauth 引擎如何将其与输入其登录名/密码凭据的用户链接(或关联)?

我不是在谈论一些 google 或 Facebook 或 twitter 或 Instagram API,而是我应该在我创建的网站中服务的一个我用 symfony2.0 制作的小狗。

我得到了完美的访问令牌,无论我需要做什么,我都拥有它。

所以问题来了。我在客户端和服务器端都需要做什么才能使整个事情将令牌与用户联系起来。换句话说,一旦我在 iOS 应用程序中获得了令牌,我需要访问一个 URL,该 URL 将响应一个包含属于用户的某些项目的 json 字符串。但目前我只是获得了身份验证表单的 HTML,因为它解释了用户尚未登录。

我编辑以指定使用 ios 应用程序和浏览器之间的差异。真的不同,但我不知道如何行动或做什么。

从iOS APP调用时调试:

[2012-09-23 01:30:43] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest". [] []
[2012-09-23 01:30:43] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onEarlyKernelRequest". [] []
[2012-09-23 01:30:43] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] []
[2012-09-23 01:30:43] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
[2012-09-23 01:30:43] security.INFO: Populated SecurityContext with an anonymous Token [] []
[2012-09-23 01:30:43] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onKernelRequest". [] []
[2012-09-23 01:30:43] request.INFO: Matched route "_get_carts_api" (parameters: "_controller": "Acme\StoreBundle\Controller\APIController::getCartsApiAction", "_route": "_get_carts_api") [] []
[2012-09-23 01:30:43] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest". [] []
[2012-09-23 01:30:44] event.DEBUG: Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::onKernelController". [] []
[2012-09-23 01:30:44] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController". [] []
[2012-09-23 01:30:44] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController". [] []
[2012-09-23 01:30:44] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController". [] []
[2012-09-23 01:30:44] event.DEBUG: Notified event "kernel.controller" to listener "JMS\SecurityExtraBundle\Controller\ControllerListener::onCoreController". [] []
[2012-09-23 01:30:44] app.INFO: anon. [] [

从浏览器使用 Web 时进行调试:

[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onEarlyKernelRequest". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". [] []
[2012-09-23 01:28:07] security.DEBUG: Read SecurityContext from the session [] []
[2012-09-23 01:28:07] security.DEBUG: Reloading user from user provider. [] []
[2012-09-23 01:28:07] doctrine.DEBUG: SET NAMES UTF8 ([]) [] []
[2012-09-23 01:28:07] doctrine.DEBUG: SELECT t0.username AS username1, t0.username_canonical AS username_canonical2, t0.email AS email3, t0.email_canonical AS email_canonical4, t0.enabled AS enabled5, t0.salt AS salt6, t0.password AS password7, t0.last_login AS last_login8, t0.locked AS locked9, t0.expired AS expired10, t0.expires_at AS expires_at11, t0.confirmation_token AS confirmation_token12, t0.password_requested_at AS password_requested_at13, t0.roles AS roles14, t0.credentials_expired AS credentials_expired15, t0.credentials_expire_at AS credentials_expire_at16, t0.id AS id17, t0.name AS name18, t0.address AS address19, t0.nif AS nif20, t0.phone AS phone21, t0.account_number AS account_number22, t0.zip AS zip23, t0.town AS town24, t0.province AS province25, t0.birth_date AS birth_date26, t0.myTestsHelpActive AS myTestsHelpActive27, t0.myPackagesHelpActive AS myPackagesHelpActive28, t0.historyHelpActive AS historyHelpActive29, t0.shopHelpActive AS shopHelpActive30, t0.sellerPackageHelpActive AS sellerPackageHelpActive31, t0.testHours AS testHours32, t0.testMinutes AS testMinutes33, t0.wrongSubstract AS wrongSubstract34, t0.archivedPackages AS archivedPackages35 FROM usuario t0 WHERE t0.username_canonical = ? (["pgbonino@gmail.com"]) [] []
[2012-09-23 01:28:07] security.DEBUG: Username "pgbonino@gmail.com" was reloaded from user provider. [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onKernelRequest". [] []
[2012-09-23 01:28:07] request.INFO: Matched route "_get_carts" (parameters: "_controller": "Acme\StoreBundle\Controller\ShopController::getCartsAction", "_route": "_get_carts") [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.request" to listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::onKernelController". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.controller" to listener "JMS\SecurityExtraBundle\Controller\ControllerListener::onCoreController". [] []
[2012-09-23 01:28:07] doctrine.DEBUG: SELECT t0.id AS id1, t0.name AS name2, t0.create_date AS create_date3, t0.update_date AS update_date4, t0.user_id AS user_id5 FROM Cart t0 WHERE t0.user_id = ? ([100]) [] []
[2012-09-23 01:28:07] doctrine.DEBUG: SELECT t0.id AS id1, t0.name AS name2, t0.description AS description3, t0.prize AS prize4, t0.update_time AS update_time5, t0.update_comment AS update_comment6, t0.active AS active7, t0.user_id AS user_id8, t0.block_id AS block_id9 FROM package t0 INNER JOIN packages_carts ON t0.id = packages_carts.package_id WHERE packages_carts.cart_id = ? ([11]) [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse". [] []
[2012-09-23 01:28:07] security.DEBUG: Write SecurityContext in the session [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\SecurityBundle\EventListener\ResponseListener::onKernelResponse". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bridge\Monolog\Handler\FirePHPHandler::onKernelResponse". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.response" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener::onKernelResponse". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse". [] []
[2012-09-23 01:28:07] event.DEBUG: Notified event "kernel.response" to listener "Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse". [] []]

编辑:这是授权和令牌请求在调试日志中所写的内容:

[2012-09-23 13:53:12] request.INFO: Matched route "fos_oauth_server_authorize" (parameters: "_controller": "FOS\OAuthServerBundle\Controller\AuthorizeController::authorizeAction", "_route": "fos_oauth_server_authorize"). Request: GET /~pgbonino/Symfony/web/app_dev.php/oauth/v2/auth?client_id=1_2854cesqrsu8oosk8k40sw0ck4kccgooowc4s80gk4gssc4g00&redirect_uri=http%3A%2F%2F127.0.0.1%2F~pgbonino%2FSymfony%2Fweb%2Fapp_dev.php%2Foauth%2Fv2%2FfalseCallBack&response_type=code HTTP/1.1
Accept:          text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-us
Connection:      keep-alive
Cookie:          PHPSESSID=o6fmhfinrfv7ueht3hmgt91jf6
Host:            127.0.0.1
Origin:          http://127.0.0.1
Referer:         http://127.0.0.1/~pgbonino/Symfony/web/app_dev.php/main/
User-Agent:      Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10A403
X-Php-Ob-Level:  1

[2012-09-23 13:53:13] request.INFO: Matched route "fos_oauth_server_token" (parameters: "_controller": "fos_oauth_server.controller.token:tokenAction", "_route": "fos_oauth_server_token"). Request: POST /~pgbonino/Symfony/web/app_dev.php/oauth/v2/token HTTP/1.1
Accept:          */*
Accept-Encoding: gzip, deflate
Accept-Language: en-us
Connection:      keep-alive
Content-Length:  312
Content-Type:    application/x-www-form-urlencoded
Host:            127.0.0.1
User-Agent:      gtm-oauth2 Gallello.PruebasAPI/1.0
X-Php-Ob-Level:  1

client_id=1_2854cesqrsu8oosk8k40sw0ck4kccgooowc4s80gk4gssc4g00&client_secret=sr93lkss5hc48kg0csw4ksk0goccsc4g00448gc8s0k4s4csk&code=UnNDaUkdl6YAkr53uwctnuZLpota6X-jSBq4gqB1XfE&grant_type=authorization_code&redirect_uri=http%3A%2F%2F127.0.0.1%2F~pgbonino%2FSymfony%2Fweb%2Fapp_dev.php%2Foauth%2Fv2%2FfalseCallBack

[2012-09-23 14:02:47] request.INFO: Matched route "_get_carts_api" (parameters: "_controller": "Acme\StoreBundle\Controller\APIController::getCartsApiAction", "_route": "_get_carts_api"). Request: GET /~pgbonino/Symfony/web/app_dev.php/api/getCarts HTTP/1.1
Accept:          */*
Accept-Encoding: gzip, deflate
Accept-Language: en-us
Connection:      keep-alive
Cookie:          PHPSESSID=6apagmbmr4b7dddf3r44ecgp30
Host:            127.0.0.1
User-Agent:      PruebasAPI/1.0 CFNetwork/609 Darwin/12.2.0
X-Php-Ob-Level:  1

接下来是我完成所有工作的 XCode:

首先,首先声明并准备执行请求的对象:

- (GTMOAuth2Authentication * ) authForPreparaTest
{
//This URL is defined by the individual 3rd party APIs, be sure to read their documentation
NSString * url_string = @"http://127.0.0.1/~pgbonino/Symfony/web/app_dev.php/oauth/v2/token";
NSURL * tokenURL = [NSURL URLWithString:url_string];
// We'll make up an arbitrary redirectURI.  The controller will watch for
// the server to redirect the web view to this URI, but this URI will not be
// loaded, so it need not be for any actual web page.
NSString * redirectURI = @"http://127.0.0.1/~pgbonino/Symfony/web/app_dev.php/oauth/v2/falseCallBack";
GTMOAuth2Authentication * myAuth;
myAuth = [GTMOAuth2Authentication authenticationWithServiceProvider:@"PreparaTest"
                                                         tokenURL:tokenURL
                                                      redirectURI:redirectURI
                                                         clientID:kMyClientID
                                                     clientSecret:kMyClientSecret
        ];
[myAuth setTokenType:@"Bearer"];
return myAuth;
}

其次,使用我的 Web 应用程序推送 Web 视图,询问用户他们的凭据:

- (void)signInToPreparaTest
{
GTMOAuth2Authentication *myAuth = [self authForPreparaTest];
NSString* auth_string = @"http://127.0.0.1/~pgbonino/Symfony/web/app_dev.php/oauth/v2/auth";
NSURL * authURL = [NSURL URLWithString:auth_string];
// Display the authentication view


GTMOAuth2ViewControllerTouch * viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:myAuth
                                                             authorizationURL:authURL
                                                             keychainItemName:nil
                                                                     delegate:self
                                                             finishedSelector:@selector(viewController:finishedWithAuth:error:)];
[viewController setBrowserCookiesURL:[NSURL URLWithString:@"http://127.0.0.1/~pgbonino/Symfony/web/app_dev.php/"]];
[self.navigationController pushViewController:viewController animated:YES];
}

第三,一切顺利,所以用 access_token 更新 self.auth 对象:

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
  finishedWithAuth:(GTMOAuth2Authentication *)myAuth
             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 = myAuth.accessToken;
    [myAuth setShouldAuthorizeAllRequests:YES];
    [self setAuth:myAuth];

    // 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];
}
}

第四次和最后一次(有问题的时刻),一旦通过身份验证,我就会使用我的 API(我想要所有已保存的购物车为登录用户):

- (IBAction)getCartsPressed:(id)sender{

NSMutableURLRequest *request = [NSMutableURLRequest new];

NSString * url_string = @"http://127.0.0.1/~pgbonino/Symfony/web/app_dev.php/api/getCarts";
NSURL *getCartsURL = [NSURL URLWithString:url_string];

[request setURL:getCartsURL];

[self.auth authorizeRequest:request
          completionHandler:^(NSError *error) {
              NSString *output = nil;
              if (error) {
                  output = [error description];
              } else {
                  // Synchronous fetches like this are a really bad idea in Cocoa applications
                  //
                  // For a very easy async alternative, we could use GTMHTTPFetcher
                  NSURLResponse *response = nil;
                  NSData *data = [NSURLConnection sendSynchronousRequest:request
                                                       returningResponse:&response
                                                                   error:&error];
                  if (data) {
                      // API fetch succeeded
                      output = [[NSString alloc] initWithData:data
                                                      encoding:NSUTF8StringEncoding];
                  } else {
                      // fetch failed
                      output = [error description];
                  }
              }
          }];
}

提前致谢

4

0 回答 0