简体   繁体   中英

Oauth 2.0 token based authentication AngularJS (Beginner)

I have gone through multiple documents , Including ng-cordova and oauth-ng but I still can't find any resource which deals with a basic token based authentication in angularjs/Ionic

I am having trouble about how to make this curl call in angularjs

curl -X POST -vu sampleapp:appkey http://sampleurl/oauth/token -H "Accept: application/json" -d "password=pwd&username=sampleuname&grant_type=password&scope=read%20write&client_secret=appkey&client_id=sampleapp"

I am doing this and it's giving me a 401 error. However a curl call works just fine.

$scope.login = function() {

            $http({
              method: "post", 
              url: "http://sampleurl/oauth/token", 
              data:  "client_id=" + clientId + "&client_secret=" + clientSecret + "password=pwd&username=sampleuser&grant_type=password" + "&scope=read%20write",
              withCredentials: true,
              headers: {
                'Content-Type': 'application/json; charset=utf-8'
                }
            })                
               .success(function(data) {
                    accessToken = data.access_token;
                    $location.path("/secure");
                })
                .error(function(data, status) {
                    alert("ERROR: " + data);
                });

}

I realise that once I get the token , I have to do something similar to

$http.get('http://apiurl/api/v1/users', 
    {headers: { Authorization: ' Token api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxx'}})
    .then(function(response) {
            service.currentUser = response.data.user;
            console.log(service.currentUser);
    });

But so far I've been unable to figure out a way to make a call to the server and save the access token in my localstorage. All resources on the internet are primarily catered towards 3rd party logins (google,facebook,twitter etc ) or JWT tokens.

I am fairly new at this but I've found out that I need to worry about password grant flow where the user gives his/her credentials to the consumer and the consumer exchanges these for an access and refresh token. Still I don't believe I am making the right call.

UPDATE : As @DanielCottone in the answer below has mentioned , oauth-ng seemed like a good solution but their documentation from what I've seen confuses me as I want to send the username and password to the url too and the sample is not implementing it or has a provision for it from what I can tell?

This is what they have in their documentation :

<oauth
  site="http://oauth-ng-server.herokuapp.com"
  client-id="d6d2b510d18471d2e22aa202216e86c42beac80f9a6ac2da505dcb79c7b2fd99"
  redirect-uri="http://localhost:9000"
  profile-uri="http://oauth-ng-server.herokuapp.com/api/v1/me"
  scope="public">
</oauth>

Again , this is a first time I'm trying integration of any kind and it makes sense for me to think that the call will have credentials sent with it? How do I send it then ?

The best way to solve this is by storing the token in localStorage after authentication, and then using an interceptor to inject the token into your request headers:

$http authentication promise (you need to inject $localStorage)

.success(function(data) {
  $localStorage.accessToken = data.access_token;
  $location.path("/secure");
})

Authentication interceptor

.factory('AuthInterceptor', function ($q, $localStorage, $rootScope) {

  return {
    request: function (config) {
      if ($localStorage.access_token) {
        config.headers['Authorization'] = 'Token api_key=' + $localStorage.token;
      }
      return config;
    },

    responseError: function (response) {
      if (response.status === 401 || response.status === 403) {
        delete $localStorage.access_token;
        // Do some kind of redirect to login page here...
      }
      return $q.reject(response);
    }
  };
});

To logout, you would just delete the token from localStorage, and all further requests would be redirected to the login page if you get a 401 or 403 from the API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM