简体   繁体   中英

Token based Authentication with Angular

I want to authenticate users through api, when username and password is right it returns a token and store on local storage using ngStorage but I read some articles that it's not secure saving token on localStorage, and they made reference to storing it to cookies Http. How can I store the token on cookies Http and is it secure or is there a better way of handling token authentication

$scope.loginUser = function(){
    $http({
      method: 'POST',
      url: 'ourdomain.com/api/token',
      headers: 
      {
          'Content-type': 'application/x-www-form-urlencoded',
      },
      data: 
      'UserName=' + $scope.username + 
      '&Password=' + $scope.password 
      }).success(function(data, status) {
               $localStorage.token = data;
               console.log(data);
      })
      .error(function(data, status) {
          console.log("Error");
      });
}

for cookie the user can disable cookie.

this link can explain you Token based vs. Cookie based

https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

and this for the difference between localStorage, sessionStorage, session and cookies : What is the difference between localStorage, sessionStorage, session and cookies?

I warmly suggest you to use stallizer: https://github.com/sahat/satellizer

Login with Email and Password

Client: Enter your email and password into the login form.

Client: On form submit call $auth.login() with email and password.

Client: Send a POST request to /auth/login. Server: Check if email exists, if not - return 401.

Server: Check if password is correct, if not - return 401.

Server: Create a JSON Web Token and send it back to the client.

Client: Parse the token and save it to Local Storage for subsequent use after page reload.

var user = {
  email: $scope.email,
  password: $scope.password
};

$auth.login(user)
  .then(function(response) {
    // Redirect user here after a successful log in.
  })
  .catch(function(response) {
    // Handle errors here, such as displaying a notification
    // for invalid email and/or password.
  });


// Controller
$scope.isAuthenticated = function() {
  return $auth.isAuthenticated();
};

<!-- Template -->
<ul ng-if="!isAuthenticated()">
  <li><a href="/login">Login</a></li>
  <li><a href="/signup">Sign up</a></li>
</ul>
<ul ng-if="isAuthenticated()">
  <li><a href="/logout">Logout</a></li>
</ul>

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