jwt_spec.rb 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
require 'spec_helper'

describe OmniAuth::Strategies::Jwt do
  include Rack::Test::Methods
  include DeviseHelpers

  context '.decoded' do
    let(:strategy) { described_class.new({}) }
    let(:timestamp) { Time.now.to_i }
    let(:jwt_config) { Devise.omniauth_configs[:jwt] }
    let(:key) { JWT.encode(claims, jwt_config.strategy.secret) }

    let(:claims) do
      {
        id: 123,
        name: "user_example",
        email: "user@example.com",
        iat: timestamp
      }
    end

    before do
      allow_any_instance_of(OmniAuth::Strategy).to receive(:options).and_return(jwt_config.strategy)
      allow_any_instance_of(Rack::Request).to receive(:params).and_return({ 'jwt' => key })
    end

    it 'decodes the user information' do
      result = strategy.decoded

      expect(result["id"]).to eq(123)
      expect(result["name"]).to eq("user_example")
      expect(result["email"]).to eq("user@example.com")
      expect(result["iat"]).to eq(timestamp)
    end

    context 'required claims is missing' do
      let(:claims) do
        {
          id: 123,
          email: "user@example.com",
          iat: timestamp
        }
      end

      it 'raises error' do
L
Lin Jen-Shin 已提交
46
        expect { strategy.decoded }.to raise_error(OmniAuth::Strategies::Jwt::ClaimInvalid)
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
      end
    end

    context 'when valid_within is specified but iat attribute is missing in response' do
      let(:claims) do
        {
          id: 123,
          name: "user_example",
          email: "user@example.com"
        }
      end

      before do
        jwt_config.strategy.valid_within = Time.now.to_i
      end

      it 'raises error' do
L
Lin Jen-Shin 已提交
64
        expect { strategy.decoded }.to raise_error(OmniAuth::Strategies::Jwt::ClaimInvalid)
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
      end
    end

    context 'when timestamp claim is too skewed from present' do
      let(:claims) do
        {
          id: 123,
          name: "user_example",
          email: "user@example.com",
          iat: timestamp - 10.minutes.to_i
        }
      end

      before do
        jwt_config.strategy.valid_within = 2.seconds
      end

      it 'raises error' do
L
Lin Jen-Shin 已提交
83
        expect { strategy.decoded }.to raise_error(OmniAuth::Strategies::Jwt::ClaimInvalid)
84 85 86 87
      end
    end
  end
end