This document contains code for configuring Doorkeeper for OAuth authentication in a Rails application. It defines resource owner authenticators to find an account from a token or credentials. It sets default and optional scopes. It customizes the Doorkeeper error response and adds authentication failure errors. It also shows code to automatically refresh an access token before expiration.
10. # This block will be called to check whether the resource owner is authenticated or not.
resource_owner_authenticator do
if (token = doorkeeper_token).present?
account = Account.find(doorkeeper_token.resource_owner_id)
session[:actor] = account
end
end
resource_owner_from_credentials do |routes|
begin
actor = Account.authenticate(username: params[:username], password: params[:password])
rescue => e
raise Doorkeeper::Errors::AuthenticationFailed
end
end
13. class Api::V1::ProductsController < Api::V1::ApiController
before_action :doorkeeper_authorize! # Requires access token
for all actions
# before_action -> { doorkeeper_authorize! :read, :write }
# your actions
end
14. module Doorkeeper
module OAuth
class ErrorResponse
def body
{ code: name, message: description }
end
end
end
module Errors
class AuthenticationFailed < DoorkeeperError
def type
:authentication_failed
end
end
end
end
15. # ALL-IN Doorkeeper
# See https://github.com/doorkeeper-gem/doorkeeper/wiki/Customizing-the-response-body-when-unauthorized
def doorkeeper_render_error_with(error)
case error.status
when :unauthorized
fail Unauthorized
when :forbidden
fail AccessDenied
end
end
16.
17.
18.
19.
watch(): void {
if (!!this.actor) {
let grant: Grant = this.actor.getGrant()!;
let isRefreshing: boolean = false;
this.intervalId = setInterval(() => {
if (!!this.actor && this.actor.isTokenExpired(grant) && !isRefreshing) {
isRefreshing = true;
this.oAuthTokenService.refreshToken(grant)
.subscribe((result: Grant) => {
if (this.actor) {
this.actor.setGrant(result);
this.actor.refresh({indicator: { isDisable: true}}).subscribe(() => {
isRefreshing = false;
});
}
grant = result;
});
}
}, 10 * 1000);
}
}