Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

After Sign-in success, The following requests on Angular side are unauthorized. #285

Closed
poc7667 opened this issue Apr 22, 2016 · 7 comments

Comments

@poc7667
Copy link

poc7667 commented Apr 22, 2016

After Signin success by email auth,

The following requests on Angular (js side) are Unauthorized.

I can not see the token in the success response,

And I guess those following requests didn't send the tokens as well.

What's the buggy point? Thanks

successful email auth on http://localhost:3000/api/v1/auth/sign_in

$auth.submitLogin({
  email: '[email protected]',
  password: '123'
})
  .then(function(resp) {
    // handle success
    // I got User information but without token
    // {id: 1, provider: "email", uid: "[email protected]", name: null, nickname: null…}
  })

I do the GET request in other controllers and got Unauthorized exception

Authentication on http://localhost:3000/api/v1/banks

I got `401 (Unauthorized)``

  app.controller('BanksIndexCtrl', function($scope, $resource, $q, bankService) {
      // this will raise Unauthorized exception
      $q.all([$scope.BankService.all().$promise]).then(function(ret){
        $scope.banks = ret[0]
      });
  });

Exception on console

      Started GET "/api/v1/banks" for 127.0.0.1 at 2016-04-22 22:51:47 +0800
      Processing by Api::V1::BanksController#index as JSON
      Filter chain halted as :authenticate_api_v1_user! rendered or redirected
      Completed 401 Unauthorized in 1ms (Views: 0.1ms | ActiveRecord: 0.0ms)

Request Header


GET /api/v1/banks HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
If-Modified-Since: Mon, 26 Jul 1997 05:00:00 GMT
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
Referer: http://localhost:3000/ngAdmin/admin.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: _session_id=2971e86420fb63b7a0d1de5c2fe97d88; remember_user_token=W1sxXSwiJDJhJDEwJE4xcWhrNVMvME51Um5GeGV5anc3UWUiLCIxNDYxMzM0NDMzLjk4ODQzODEiXQ%3D%3D--bcb30c131693a6ebdd638c835f7acdc4202abb66; _ga=GA1.1.381527585.1455597511; _AlphaLoan_session=UitEN3l5WHNKdFpnV0dVWXYyUlRnYTlmdW9pUE9Oa0wydFFMWUw4c3E1Um5zaytsMmdZcy8wb01PbU9WOVA3dm9mRjUzLzRKdmQ1cmw0WDhsY0lPc3RGVTA3YUdSYm5sVXN6Rmpnd25EaU4rWTE3ZU9FakRYWHVyalJ3OTg4eGQ0RnhYWDRqMXRwazh6bmlRdk82eDM1ZzhYQk1lelRFSmVtZXc0ZTdsSGUzczJpSlhsenk0ZC9pK0k5d0wvRXpUNTNhenBsVzUwaVBONlFIOWQ5THR4MS9VS3BiQVF5NEhyVW1JNnF4N2prQXRkVGhpb2psZEZTdHNoelN2L1VzWTVBTVQ2VzlKcnE5N0I5OWVGRUlmbHFyb3NTTUZ6cHZwc2UwbW4wMWgranR4YTJHZ3V6Nm1CTVNVUTllditFMktNbDBGODNucUcydHYzT3Q1eEZyaTlnPT0tLTg4bXVLa1lFZ1NER1J6RFhGWFNyaXc9PQ%3D%3D--97b510524e0a6b970ef6ad26d87d83fadb80f51c

routes.rb

Rails.application.routes.draw do
  devise_for :users  , :controllers => {:registrations => "registrations"}
  namespace :api do
    namespace :v1, defaults: {format: 'json'} do
      mount_devise_token_auth_for 'User', at: 'auth', controllers: {
        sessions: 'token_sessions'
      }
  ...      

api/v1/banks.rb

class Api::V1::BanksController < ApplicationController
  skip_before_action :protect_from_forgery
  protect_from_forgery with: :null_session, only: Proc.new { |c| c.request.format.json? }
  before_filter :authenticate_api_v1_user!
  ...

application.rb

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*',
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :options, :head],
      :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
      :max_age => 0
  end
end

Angular App config

app.config(function($authProvider) {
    $authProvider.configure({
        apiUrl: '/',
        tokenValidationPath: 'api/v1/auth/validate_token',
        signOutUrl: 'api/v1/auth/sign_out',
        emailRegistrationPath: 'api/v1/auth',
        accountUpdatePath: 'api/v1/auth',
        accountDeletePath: 'api/v1/auth',
        confirmationSuccessUrl: window.location.href,
        passwordResetPath: 'api/v1/auth/password',
        passwordUpdatePath: 'api/v1/auth/password',
        passwordResetSuccessUrl: window.location.href,
        emailSignInPath: 'api/v1/auth/sign_in',
        storage: 'cookies',
        forceValidateToken: false,
        validateOnPageLoad: true,
        proxyIf: function() {
            return false;
        },
        proxyUrl: '/proxy',
        omniauthWindowType: 'sameWindow',
        authProviderPaths: {
            alphaloan: 'api/v1/auth/alphaloan',
            github: 'api/v1/auth/github',
            facebook: 'api/v1/auth/facebook',
            google: 'api/v1/auth/google'
        },
        tokenFormat: {
            "access-token": "{{ token }}",
            "token-type": "Bearer",
            "client": "{{ clientId }}",
            "expiry": "{{ expiry }}",
            "uid": "{{ uid }}"
        },
        cookieOps: {
            path: "/",
            expires: 9999,
            expirationUnit: 'days',
            secure: false,
            domain: 'domain.com'
        },
        createPopup: function(url) {
            return window.open(url, '_blank', 'closebuttoncaption=Cancel');
        },
        parseExpiry: function(headers) {
            // convert from UTC ruby (seconds) to UTC js (milliseconds)
            return (parseInt(headers['expiry']) * 1000) || null;
        },
        handleLoginResponse: function(response) {
            return response.data;
        },
        handleAccountUpdateResponse: function(response) {
            return response.data;
        },
        handleTokenValidationResponse: function(response) {
            return response.data;
        }
    });
});
@poc7667
Copy link
Author

poc7667 commented Apr 23, 2016

Update

Server response after login

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Sat, 23 Apr 2016 02:00:23 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
access-token: D6N2QVAU6aQn4LaalXy2uw
token-type: Bearer
client: 5Jv3tlVZ3p4T926J2BPDvg
expiry: 1462586423
uid: [email protected]
ETag: W/"dbfbb571a147b8aa69a9bc4170445497"
Cache-Control: max-age=0, private, must-revalidate
X-Meta-Request-Version: 0.3.4
X-Request-Id: 4cc9186c-8f92-4934-a540-d87f5adb4422
X-Runtime: 0.857113
Access-Control-Allow-Origin: http://dev.co
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS, HEAD
Access-Control-Expose-Headers: *
Access-Control-Max-Age: 0
Access-Control-Allow-Credentials: true
Vary: Origin

The user response in the console (No token information)

![inline](https://i.imgur.com/5cmaKUU.png=300x "Title")

Subsequent requests are failed.

Because the Subsequent requests don't contain any token in the header

bankRestService().update(bank, id)

configuration

    app.config(function($authProvider) {
        $authProvider.configure({
            apiUrl: '/api/v1/',
            tokenValidationPath: '/auth/validate_token',
            signOutUrl: '/auth/sign_out',
            emailRegistrationPath: '/auth',
            accountUpdatePath: '/auth',
            accountDeletePath: '/auth',
            confirmationSuccessUrl: window.location.href,
            passwordResetPath: '/auth/password',
            passwordUpdatePath: '/auth/password',
            passwordResetSuccessUrl: window.location.href,
            emailSignInPath: '/auth/sign_in',
            storage: 'cookies',
            forceValidateToken: false,
            validateOnPageLoad: true,
            proxyIf: function() {
                return false;
            },
            proxyUrl: '/proxy',
            omniauthWindowType: 'sameWindow',
            authProviderPaths: {
                alphaloan: '/auth/alphaloan',
                github: '/auth/github',
                facebook: '/auth/facebook',
                google: '/auth/google'
            },
            tokenFormat: {
                "access-token": "{{ token }}",
                "token-type": "Bearer",
                "client": "{{ clientId }}",
                "expiry": "{{ expiry }}",
                "uid": "{{ uid }}"
            },
            cookieOps: {
                path: "/",
                expires: 9999,
                expirationUnit: 'days',
                secure: false,
                domain: 'domain.com'
            },
            createPopup: function(url) {
                return window.open(url, '_blank', 'closebuttoncaption=Cancel');
            },
            parseExpiry: function(headers) {
                // convert from UTC ruby (seconds) to UTC js (milliseconds)
                return (parseInt(headers['expiry']) * 1000) || null;
            },
            handleLoginResponse: function(response) {
                return response.data;
            },
            handleAccountUpdateResponse: function(response) {
                return response.data;
            },
            handleTokenValidationResponse: function(response) {
                return response.data;
            }
        });
    });    

@poc7667
Copy link
Author

poc7667 commented Apr 24, 2016

I fixed the cookie not persisted by changing storage: 'cookies', to storage: 'localStorage', however, I don't know the reason LOL

@poc7667 poc7667 closed this as completed Apr 24, 2016
@FredHasselot
Copy link

Now you are logged on reload and you can see token. right? But are you able to post on api with a filter on server side that need user to be logged.

I still cant. Do you have an interceptor or something to add token to the post request, on your angular app?

@poc7667
Copy link
Author

poc7667 commented Apr 25, 2016

@FredHasselot Today, I did another auth token module again, it works.
You can refer to my post for the brief introduction thanks ~

http://poc7667.github.io/2016/04/25/token-auth/

@FredHasselot
Copy link

@poc7667 Thanks a lot for the link.

@CJYate
Copy link

CJYate commented Jan 9, 2017

@poc7667 link now broken

I'm seeing the same problem.

@erijonhson
Copy link

http://poc7667.github.io/2016/04/25/token-auth/ don't work. Help us, please...

erijonhson added a commit to erijonhson/ng-token-auth that referenced this issue Oct 1, 2017
I had the same problem as described here: lynndylanhurley#285
Fix it the same way.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants