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

add required option for oauth2 middleware #511

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ Next Release

#### Features
* [#510](https://github.com/intridea/grape/pull/510): Support lambda-based default values for params - [@myitcv](https://github.com/myitcv).
* [#511](https://github.com/intridea/grape/pull/511): Add `required` option for OAuth2 middleware - [@bcm](https://github.com/bcm).
* Your contribution here.

#### Fixes
Expand Down
5 changes: 3 additions & 2 deletions lib/grape/middleware/auth/oauth2.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ def default_options
realm: 'OAuth API',
parameter: %w(bearer_token oauth_token),
accepted_headers: %w(HTTP_AUTHORIZATION X_HTTP_AUTHORIZATION X-HTTP_AUTHORIZATION REDIRECT_X_HTTP_AUTHORIZATION),
header: [/Bearer (.*)/i, /OAuth (.*)/i]
header: [/Bearer (.*)/i, /OAuth (.*)/i],
required: true
}
end

Expand Down Expand Up @@ -53,7 +54,7 @@ def verify_token(token)
error_out(403, 'insufficient_scope')
end
end
else
elsif !!options[:required]
error_out(401, 'invalid_token')
end
end
Expand Down
27 changes: 26 additions & 1 deletion spec/grape/middleware/auth/oauth2_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class FakeToken
attr_accessor :token

def self.verify(token)
FakeToken.new(token) if %w(g e).include?(token[0..0])
FakeToken.new(token) if !!token && %w(g e).include?(token[0..0])
end

def initialize(token)
Expand Down Expand Up @@ -87,4 +87,29 @@ def app
it { @err[:headers]['WWW-Authenticate'].should == "OAuth realm='OAuth API', error='insufficient_scope'" }
it { @err[:status].should == 403 }
end

context 'when authorization is not required' do
def app
Rack::Builder.app do
use Grape::Middleware::Auth::OAuth2, token_class: 'FakeToken', required: false
run lambda { |env| [200, {}, [(env['api.token'].token if env['api.token'])]] }
end
end

context 'with no token' do
before { post '/awesome' }

it 'succeeds anyway' do
last_response.status.should == 200
end
end

context 'with a valid token' do
before { get '/awesome?oauth_token=g123' }

it 'sets env["api.token"]' do
last_response.body.should == 'g123'
end
end
end
end