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. #619

Closed
poc7667 opened this issue Apr 22, 2016 · 2 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: 'sample@gmail.com',
  password: '123'
})
  .then(function(resp) {
    // handle success
    // I got User information but without token
    // {id: 1, provider: "email", uid: "sample@gmail.com", 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 24, 2016

Be sure to install the latest gem version.
It was 0.1.31,
some bugs fixed at 0.1.37

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

@poc7667 Hi, were you able to solve it? Even now I see similar error in my implementation.I tried implementing for API. When I call custom controller, I see below error.
{
"errors": [
"Use POST /sign_in to sign in. GET is not supported."
]
}

In console, I see

Started GET "/v1/names" for 127.0.0.1 at 2016-10-29 21:46:57 +0530
Processing by Api::V1::NamesController#index as /
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)

Started GET "/auth/sign_in" for 127.0.0.1 at 2016-10-29 21:46:57 +0530
Processing by DeviseTokenAuth::SessionsController#new as /
User Load (1.0ms) SELECT users.* FROM users WHERE users.uid = 'admin@factor.in' LIMIT 1
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Hash (0.0ms)
Completed 405 Method Not Allowed in 124ms (Views: 122.5ms | ActiveRecord: 1.0ms)

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

2 participants