ms-id-token-validator 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 5ca3f629dd20506004d630d41dcce5d4ec5018df
4
+ data.tar.gz: f3659bc2b9d880e4bfbc0cd373ef39c65c9d0ac4
5
+ SHA512:
6
+ metadata.gz: ec2d3ea4a273a319f3e1673bd9e5544c6ce1ef664c205edc31311cbad2a7d46db6ad434256bc3a357a5d73a9c44fa55b2702234a16f74c7c9a9b1a9115cf9a1a
7
+ data.tar.gz: c41caeb2785fac8e38c70038df5f55c7fa581f777c0024dbbbee093dc23824923717ecec7dd8212c269a17dfd2bb1bc8b3132bbc8c5c716e2b4352ee3e42ec4f
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2.4
5
+ before_install: gem install bundler -v 1.15.4
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in ms-id-token-validator.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 QQ
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # MsIdTokenValidator
2
+
3
+ This library is provided to validate id token from Microsoft Oauth2.
4
+
5
+ Inspired from the [Google ID Token](https://github.com/google/google-id-token)
6
+
7
+ ### Disclaimer
8
+ I am entirely not affiliated with Microsoft, the code is provided as-is and no warranty.
9
+
10
+ ## Installation
11
+
12
+ Add this line to your application's Gemfile:
13
+
14
+ ```ruby
15
+ gem 'ms-id-token-validator'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself as:
23
+
24
+ $ gem install ms-id-token-validator
25
+
26
+ ## Usage
27
+
28
+ ```ruby
29
+ validator = MsIdToken::Validator.new
30
+
31
+ begin
32
+ # audience is possibly the Application Client ID
33
+ payload = validator.check(id_token, audience)
34
+ rescue MsIdToken::IdTokenExpired => ex
35
+ puts 'Id token is expired'
36
+ end
37
+
38
+ ```
39
+
40
+ ## References
41
+
42
+ [Certificate credentials for application authentication](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials)
43
+
44
+ [Validate an Exchange identity token](https://docs.microsoft.com/en-us/outlook/add-ins/validate-an-identity-token)
45
+
46
+ [Azure Active Directory v2.0 tokens reference](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-tokens)
47
+
48
+ [Azure AD token reference](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-token-and-claims)
49
+
50
+ ## Development
51
+
52
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
53
+
54
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
55
+
56
+ ## Contributing
57
+
58
+ Bug reports and pull requests are welcome on GitHub at https://github.com/quangquach/ms-id-token-validator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
59
+
60
+ ## License
61
+
62
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "ms-id-token-validator"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ require "pry"
11
+ Pry.start
12
+
13
+ #require "irb"
14
+ #IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,5 @@
1
+ module MsIdToken
2
+ class Validator
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,108 @@
1
+ require 'net/http'
2
+ require 'json/jwt'
3
+
4
+ module MsIdToken
5
+ class BadIdTokenFormat < StandardError; end
6
+ class BadIdTokenHeaderFormat < StandardError; end
7
+ class BadIdTokenPayloadFormat < StandardError; end
8
+ class UnableToFetchMsConfig < StandardError; end
9
+ class UnableToFetchMsCerts < StandardError; end
10
+ class BadPublicKeysFormat < StandardError; end
11
+ class UnableToFindMsCertsUri < StandardError; end
12
+ class InvalidAudience < StandardError; end
13
+ class IdTokenExpired < StandardError; end
14
+ class IdTokenNotYetValid < StandardError; end
15
+
16
+ class Validator
17
+ MS_CONFIG_URI = 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration'.freeze
18
+ CACHED_CERTS_EXPIRY = 3600
19
+ TOKEN_TYPE = 'JWT'.freeze
20
+ TOKEN_ALGORITHM = 'RS256'.freeze
21
+
22
+ def initialize(options={})
23
+ @cached_certs_expiry = options.fetch(:expiry, CACHED_CERTS_EXPIRY)
24
+ end
25
+
26
+ def check(id_token, audience)
27
+ encoded_header, encoded_payload, signature = id_token.split('.')
28
+
29
+ raise BadIdTokenFormat if encoded_payload.nil? || signature.nil?
30
+
31
+ header = JSON.parse(Base64.decode64(encoded_header), symbolize_names: true)
32
+
33
+ public_keys = JSON::JWK::Set.new(ms_public_keys)
34
+
35
+ payload = JSON::JWT.decode(id_token, public_keys).symbolize_keys
36
+
37
+ verify_payload(payload, audience)
38
+
39
+ payload
40
+ end
41
+
42
+ private
43
+
44
+ def verify_header(header)
45
+ valid_header = header[:typ] == TOKEN_TYPE && header[:alg] == TOKEN_ALGORITHM
46
+
47
+ valid_header &= !(header[:kid].nil? && header[:x5t].nil?)
48
+
49
+ raise BadIdTokenHeaderFormat unless valid_header
50
+ end
51
+
52
+ def verify_payload(payload, audience)
53
+ if payload[:aud].nil? ||
54
+ payload[:exp].nil? ||
55
+ payload[:nbf].nil? ||
56
+ payload[:sub].nil? ||
57
+ payload[:iss].nil? ||
58
+ payload[:iat].nil? ||
59
+ payload[:tid].nil? ||
60
+ payload[:iss].match(/https:\/\/login\.microsoftonline\.com\/(.+)\/v2\.0/).nil?
61
+ raise BadIdTokenPayloadFormat
62
+ end
63
+
64
+ raise InvalidAudience if payload[:aud] != audience
65
+
66
+ current_time = Time.current.to_i
67
+
68
+ raise IdTokenExpired if payload[:exp] < current_time
69
+
70
+ raise IdTokenNotYetValid if payload[:nbf] > current_time
71
+ end
72
+
73
+ def ms_public_keys
74
+ if @ms_public_keys.nil? || cached_certs_expired?
75
+ @ms_public_keys = fetch_public_keys
76
+ @last_cached_at = Time.current.to_i
77
+ end
78
+
79
+ @ms_public_keys
80
+ end
81
+
82
+ def fetch_public_keys
83
+ ms_certs_uri = fetch_ms_config[:jwks_uri]
84
+
85
+ raise UnableToFindMsCertsUri if ms_certs_uri.nil?
86
+
87
+ uri = URI(ms_certs_uri)
88
+ response = Net::HTTP.get_response(uri)
89
+
90
+ raise UnableToFetchMsConfig unless response.is_a?(Net::HTTPSuccess)
91
+
92
+ JSON.parse(response.body, symbolize_names: true)
93
+ end
94
+
95
+ def fetch_ms_config
96
+ uri = URI(MS_CONFIG_URI)
97
+ response = Net::HTTP.get_response(uri)
98
+
99
+ raise UnableToFetchMsConfig unless response.is_a?(Net::HTTPSuccess)
100
+
101
+ JSON.parse(response.body, symbolize_names: true)
102
+ end
103
+
104
+ def cached_certs_expired?
105
+ !(@last_cached_at.is_a?(Integer) && @last_cached_at + @cached_certs_expiry >= Time.current.to_i)
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,41 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "ms-id-token-validator/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "ms-id-token-validator"
8
+ spec.version = MsIdToken::Validator::VERSION
9
+ spec.authors = ["QQ"]
10
+ spec.email = ["me@quang.be"]
11
+
12
+ spec.summary = %q{Validate the Microsoft Oauth2 ID token}
13
+ spec.description = %q{Validate the id token from Microsoft oauth2 service}
14
+ spec.homepage = "https://github.com/quangquach/ms-id-token-validator"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata["allowed_push_host"] = 'https://rubygems.org'
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against " \
23
+ "public gem pushes."
24
+ end
25
+
26
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
27
+ f.match(%r{^(test|spec|features)/})
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ spec.add_runtime_dependency('json-jwt', '~> 1.7')
34
+
35
+ spec.add_development_dependency "bundler", "~> 1.15"
36
+ spec.add_development_dependency "rake", "~> 10.0"
37
+ spec.add_development_dependency "rspec", "~> 3.0"
38
+ spec.add_development_dependency('pry', '~> 0')
39
+ spec.add_development_dependency('pry-doc', '~> 0')
40
+ spec.add_development_dependency('timecop', '~> 0')
41
+ end
metadata ADDED
@@ -0,0 +1,155 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ms-id-token-validator
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - QQ
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-10-22 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: json-jwt
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.7'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.7'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.15'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.15'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pry
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: pry-doc
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: timecop
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ description: Validate the id token from Microsoft oauth2 service
112
+ email:
113
+ - me@quang.be
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - ".rspec"
120
+ - ".travis.yml"
121
+ - Gemfile
122
+ - LICENSE.txt
123
+ - README.md
124
+ - Rakefile
125
+ - bin/console
126
+ - bin/setup
127
+ - lib/ms-id-token-validator.rb
128
+ - lib/ms-id-token-validator/version.rb
129
+ - ms-id-token-validator.gemspec
130
+ homepage: https://github.com/quangquach/ms-id-token-validator
131
+ licenses:
132
+ - MIT
133
+ metadata:
134
+ allowed_push_host: https://rubygems.org
135
+ post_install_message:
136
+ rdoc_options: []
137
+ require_paths:
138
+ - lib
139
+ required_ruby_version: !ruby/object:Gem::Requirement
140
+ requirements:
141
+ - - ">="
142
+ - !ruby/object:Gem::Version
143
+ version: '0'
144
+ required_rubygems_version: !ruby/object:Gem::Requirement
145
+ requirements:
146
+ - - ">="
147
+ - !ruby/object:Gem::Version
148
+ version: '0'
149
+ requirements: []
150
+ rubyforge_project:
151
+ rubygems_version: 2.4.8
152
+ signing_key:
153
+ specification_version: 4
154
+ summary: Validate the Microsoft Oauth2 ID token
155
+ test_files: []