Is there a way for me to use a custom OAuth implementation built into my web application with any of ionic/cordova’s plugins? I have searched on it but it is all for google/facebook social networks.
Yes !
You can call your API (with Oauth implementation) build with .NET WebApi for exemple without cordova plugin but just with $http.
I have already do this.
Hi Tomadj, do you have an example code for login? I have a user, password, client id and client secret that posts to the API to get the access_token, token_expiry and token_type(bearer)
So !
-
Login and get token from .NET WebApi 2 :
var host = hostService.getHost()+"/token";
var data = “grant_type=password&username=” + loginData.userName + “&password=” + loginData.password;$http.post(host,data, { headers: { ‘Content-Type’: ‘application/x-www-form-urlencoded’}}).success(function(response){
//save the return token in the storage
localStorageService.set(‘authorizationData’, { token: response.access_token,…});});
-
Call secure ressources with token set in the header. I use an InterceptorService for set header in each request :
‘use strict’;
App.factory(‘authInterceptorService’, [’$q’, ‘$injector’, ‘localStorageService’, function ($q,$injector, localStorageService) {var authInterceptorServiceFactory = {};
var _request = function (config) {
config.headers = config.headers || {}; var authData = localStorageService.get('authorizationData'); if (authData) { config.headers.Authorization = 'Bearer ' + authData.token; } return config;
};
var _responseError = function (rejection) {
if (rejection.status === 401) {
$injector.get(’$state’).transitionTo(‘tab.account’);
}
return $q.reject(rejection);
};authInterceptorServiceFactory.request = _request;
authInterceptorServiceFactory.responseError = _responseError;return authInterceptorServiceFactory;
}]); -
Use InterceptorService in your app.js :
App.config([’$httpProvider’,‘localStorageServiceProvider’, function($httpProvider){
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common[‘X-Requested-With’];$httpProvider.interceptors.push(‘authInterceptorService’);
}]);
I hope can help !
hey i implemented this in a similar way.
But instead of an interceptor i have an own reques service… there is a send function, where you can add a parameter “authorization” (true or false) if you want to add the auth header.
@tomadj - What JS did you include to use localStorageProvider? Is it built-in into ionic framework?
Edit: I found out it was: https://github.com/grevory/angular-local-storage
yes yes that’s right !