angularjs – 验证Angular js模块的Apigility

前端之家收集整理的这篇文章主要介绍了angularjs – 验证Angular js模块的Apigility前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Apigility创建了一个API。
我正在尝试为我正在使用API​​构建的前端应用程序设置身份验证系统。

但是我用于此认证系统的所有角度认证模块与Apigility oAuth 2实现不匹配:

> https://github.com/lynndylanhurley/ng-token-auth该模块的问题是它不允许CORS。但是它允许使用角色代码所在的服务器上的代理发送CORS请求,这是使用Guzzle在PHP中编写的。但是,代理ng-token-auth发送请求两次,即使所有验证数据都为false。
> https://github.com/sahat/satellizer此模块需要实现JWT,但在Apigility Authentication部分中,我没有看到任何文档。

我需要一个帮助来完成我的项目。

我将尝试给出一个完整的方法,我如何使 ng-token-auth与ZF2一起工作。首先,ng-token-auth使用ruby模块工作正常。所以要使它与ZF2工作:

使用以下代码解决CORS问题:

//HttpProvider
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common['Access-Control-Request-Method'] = "POST,GET,PUT,DELETE";
$httpProvider.defaults.headers.common['Origin'] = "http://xxxxxxxxxxxxxxx";
$httpProvider.defaults.headers.common['Accept'] = "application/json";
$httpProvider.defaults.headers.common['Content-Type'] = "application/json; text/html";
delete $httpProvider.defaults.headers.common['X-Requested-With'];

使用ZFCORS解决ZF2上的CORS问题,如@josilber和@ sven-lauterbach answer中所述

ZF2发送的格式响应,以使用这些代码行与ng-token-auth一起使用

$http.defaults.transformResponse = function(value,headerGetters){
    var response_header = headerGetters(),response_data   = JsonHelper.IsJsonString(value) ? JSON.parse(value) : value;
    if(response_data){
        if(response_data.access_token)
            response_header['access_token']  = response_data.access_token;
        if(response_data.expires_in){
            var now = new Date().getTime();
            response_header['expires_in']    = now + ( parseInt(response_data.expires_in,10) * 1000 );
        } 
        if(response_data.token_type)
            response_header['token_type']    = response_data.token_type;
        if(response_data.refresh_token)
            response_header['refresh_token'] = response_data.refresh_token;
        if(response_data.scope)
            response_header['scope']         = response_data.scope;
        return response_data;
    }
};

可能这不是在AngularJS中转换响应的最佳方法,但它解决了格式化OAuth2响应的问题,该功能与ng-token-auth

最后,要使用验证令牌向服务器发送请求,并自动刷新令牌,则需要更改ng-token-auth的某些行为。我使用AngularJS上的装饰图案来解决这些代码片段的问题:

在app.js中

//Change behavior of oauth2 module 
$provide.decorator("$auth",function($delegate,ApiAuthService){
    return ApiAuthService($delegate);
});

ApiAuthService是由这段代码定义的工厂:

AuthProviderService.factory('ApiAuthService',['MeService',function( MeService ){
    return function($delegate){
        return {
            initialize: function(){ return $delegate.initialize(); },apiUrl: function(configName){ },retrieveData: function(key){ return $delegate.retrieveData(key); },getConfig: function(name){ return $delegate.getConfig(name); },getExpiry: function(){  return $delegate.getExpiry(); },setAuthHeaders: function(h){ return $delegate.setAuthHeaders(h); },/*persistData: function(key,val,configName){ return $delegate.persistData(key,configName); },*/
            rejectDfd: function(reason){ $delegate.rejectDfd(reason); },invalidateTokens: function(){ return $delegate.invalidateTokens(); },submitLogin: function(params,opts){ return $delegate.submitLogin(params,opts); },validateUser: function(opts){  
                result = $delegate.validateUser(opts);
                return result;
            },deleteData: function(key){  
                return $delegate.deleteData(key);
            }
        };
    };
}]).config(['$httpProvider',function($httpProvider) {

    $httpProvider.interceptors.push([
         '$injector',function($injector) {
           return {
             request: function(req) {
               $injector.invoke([
                 '$http','$auth',function($http,$auth) {
                   var key,_ref,_results = [];
                   if (req.url.match($auth.apiUrl())) {
                     _ref = $auth.retrieveData('auth_headers');
                     //Inject value into body of request 
                     for (key in _ref) {
                         //Set Authorization request header.
                         if(key.match('access_token')){
                             if(req.headers){
                                 req.headers['Authorization'] = 'Bearer ' + _ref[key]; 
                             }else{
                                 req.headers = {'Authorization': 'Bearer ' + _ref[key]};
                             }
                         }
                         if(req.headers[key]){
                             delete req.headers[key];
                         }
                     }
                     return _results;
                   }
                 }
               ]);
               return req;
             }
           };
         }
       ]);
}]);

最后我的ng-token-auth配置是:

//OAuth2 Module configs
$authProvider.configure([ {
    "default": {
        apiUrl:                  API_URL,tokenValidationPath:     '/me',signOutUrl:              '/oauth',emailRegistrationPath:   '/oauth',accountUpdatePath:       '/oauth',accountDeletePath:       '/oauth',confirmationSuccessUrl:  window.location.href,passwordResetPath:       '/oauth',passwordUpdatePath:      '/oauth',passwordResetSuccessUrl: window.location.href,emailSignInPath:         '/oauth',forceHardRedirect: true,storage:                 'localStorage',proxyIf:                 function() { return false; },proxyUrl:                'proxy',authProviderPaths: {
            github:   '/auth/github',facebook: '/auth/facebook',google:   '/auth/google'
        },tokenFormat: {
            "access_token" : "{{ token }}","token_type"   : "Bearer","refresh_token": "{{ clientId }}","expires_in"   : "{{ expiry }}","scope"        : "{{ uid }}"
        },parseExpiry: function(headers) {
            var expires_in = parseInt(headers['expires_in'],10) || null;
                return expires_in;
            },handleLoginResponse: function(response) {
                //Patch for persistant data as library retreive auth data from header.
                return response;
            },handleAccountResponse: function(response) {
                return response;
            },handleTokenValidationResponse: function(response) {
                return response;
            }
        }
} ]);

@JerinKAlexander我希望这些步骤将帮助您找到更好的方式来解决您的问题。

原文链接:https://www.f2er.com/angularjs/144810.html

猜你在找的Angularjs相关文章