I am trying to implement an authentication for my rails API following this tutorial from railscast. I'm using the method authenticate_or_request_with_http_token, which I should check the token inside the block and it should pass if the block returns true. However, the method never pass even when I just put true in the block. This is what I see in the log:
I am using rails 4.0
Filter chain halted as :restrict_access rendered or redirected
This is my code:
before_filter :restrict_access
def restrict_access
authenticate_or_request_with_http_token do |token, options|
true
end
end
You backend have to supply authentication header. For example - 'Authorization' => "Token token=#{#token}". If method doesn't find the header it returns http status 403:Access forbidden
In case you're using Postman, I got it to work with the following config:
Authorization Type: "API Key"
key: "Authorization"
value: "Token YOUR_TOKEN" (i.e. "Token abcd1234")
Add To: "Header"
Related
An error - “jwksError: Not Found” is thrown when I make a get request with the correct bearer token in the request header to my protected API. I’ve followed the start up guide to create the jwtCheck helper function that I pass to all my routes to protect them. I need help clarifying what this error actually means thanks!
Here I define the helper function jwtCheck which will be used to secure all routes.
var jwtCheck = jwt({
secret: jwksClient.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: https://${auth0Domain}/.well-known/jwks.json,
}),
algorithms: ['RS256'],
issuer: https://${auth0Domain}/,
audience: auth0ApiIdentifier,
});
Then I protect my api using jwtCheck defined above like so. After which the api will throw an Unauthorized Error if one tries to send http requests to it without a header in the request with the auth bearer token.
const app = express();
...
app.use(jwtCheck);
...
I get new Bearer tokens by sending a POST request to auth0apiIdentifier/oauth/token and putting the following in the req body:
{
"client_id":id,
"client_secret":secret,
"audience":auth0apiIdentifier,
"grant_type":"client_credentials"
}
After sending the get request via postman with the appropriate bearer token in place, rwks-rsa module throws the subsequent error:
JwksError: Not found.
at ../server/node_modules/jwks-rsa/lib/JwksClient.js:119:23
at ../server/node_modules/jwks-rsa/lib/wrappers/request.js:36:12
at processTicksAndRejections (internal/process/task_queues.js:93:5)
Img 1 - POST request to get new auth Bearer token from Auth0
Img 2 - GET request sent with postman and corresponding error thrown by jwks-rsa module.
I've fixed it! The error was way too ambiguous but after desperation set in, I checked my configs again and I found that I included a "/" at the end of my auth0apiIdentifier, this allowed a "//" in the jwksUri which caused the issue. Solving this typo was my fix.
Check your code guys! Peace!
I'm building a demo application in clojurescript with KeeFrame and to retrieve a part of the information for this website I need to call an external API which requires a custom HTTP header parameter in the GET requests
I'm using re-frame.core for the API calls, which uses ajax.core.
I also tried to replace this with cljs-http.client. However the result is the same.
I already managed to add custom header parameters to the request header by using clj-http at server site. But this is not a solution I want to implement for this website because that means that I first have to rebuild the API I'm calling. So I can use it from my clojurescript without the parameter.
This code works. A correct GET request is generated
{:http-xhrio {
:method :get
:uri (str transuri "/acquirer/" 673072009 "/acquirerref/" acquirerRefNo)
:headers {"Accept" "application/json"}
:response-format (http/json-response-format {:keywords? true})
:on-failure [:common/set-error]}}
With "Accept: application/json" as a request header
This code does not work. Instead of a GET request an OPTIONS request is generated
{:http-xhrio {
:method :get
:uri (str transuri "/acquirer/" 673072009 "/acquirerref/" acquirerRefNo)
:headers {"Accept" "application/json" "Custom" "Value"}
:response-format (http/json-response-format {:keywords? true})
:on-failure [:common/set-error]}}
And in the request header "Accept: application/json" is not visible but "Access-Control-Request-Headers: custom" is
I expected a GET request with "Accept: application/json" and "Custom: Value" in the request header.
Can someone tell me what I'm doing wrong or provide me with a link with information about this?
Thanks in advance
The Browser will send a "preflight" OPTIONS request to verify that it is allowed to send the "Custom" request header. The server is supposed to approve by replying with "Access-Control-Allow-Headers".
See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I have not used KeeFrame, but I have a working example using a new re-frame lib I'm working on. It invokes an ajax request using this interceptor:
(def ajax-intc
"Interceptor for performing AJAX requests"
(interceptor
{:id :ajax-intc
:enter identity
:leave (fn [ctx] ; #todo (with-result ctx ...)
(let [ajax (:ajax ctx)]
;(t/spyx :ajax-intc-start ctx)
;(t/spyx :ajax-intc-start ajax)
(when-not (nil? ajax)
(t/spy :awt-ajax-intc--ajax ajax)
(let [method (t/grab :method ajax)
uri (t/grab :uri ajax)
ajax-opts-present (set/intersection (set (keys ajax)) ajax-options-keys)
opts-map (t/submap-by-keys ajax ajax-opts-present)]
;(t/spy :ajax-intc-ready (t/vals->map method uri opts-map))
(condp = method
:get (do
(t/spy :awt-ajax-intc--opts-map opts-map)
(ajax/GET uri opts-map))
:put (ajax/PUT uri opts-map)
:post (ajax/POST uri opts-map)
(throw (ex-info "ajax-intc: unrecognized :method" ajax))))))
ctx)}))
When invoked with this event:
(flame/dispatch-event [:ajax-demo :get "/fox.txt"
{:handler ajax-handler
:error-handler ajax-error-handler
:headers {"custom" "something"}
}])
one can see in the Chrome dev console that the headers come through:
:awt-localstore-load-intc--loaded-value-1 {}
core.cljs:192 :awt-ajax-intc--ajax => {:method :get, :uri "/fox.txt", :handler #object[flintstones$core$ajax_handler], :error-handler #object[flintstones$core$ajax_error_handler], :headers {"custom" "something"}}
core.cljs:192 :awt-ajax-intc--opts-map => {:handler #object[flintstones$core$ajax_handler], :error-handler #object[flintstones$core$ajax_error_handler], :headers {"custom" "something"}}
If you want to try it out, you can clone this repo: git#github.com:cloojure/cljs-enflame.git
and then run:
lein clean
lein figwheel
and see it run in the browser.
Im having a problem for creating a resource, when i make a POST request to my route.
My route looks like:
Route::group(array('prefix' => 'api/v1', 'before' => 'oauth'), function()
{
//Media Route
Route::resource('media', 'PostController',['except' => ['create', 'edit']]);
});
when i post the resource it says i should provide an valid access token, but i already doing that. This is the resource uri.
appname.dev/api/v1/media/?access_token=ksfdkfjkfsj
even with:
appname.dev/api/v1/media?access_token=ksfdkfjkfsj
it doesn't work it throws an error with json response
"error": "invalid_request",
"error_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"access token\" parameter."
I'm testing this with the Postman plugin in chrome and using the lucadegasperi oauth2-server package for laravel.
What am i doing wrong?
Thx in advance
I created a new developer account and I am having a problem authenticating with the REST API.
POST https://rest.developer.yodlee.com/services/srest/restserver/v1.0/authenticate/coblogin
{ cobrandLogin: 'sbCob*****',
cobrandPassword: '**********' }
the system responds with:
{ Error: [ { errorDetail: 'Internal Core Error has occurred' } ] }
am I doing something wrong?
I am testing the API with Postman and apparently I need to send the params with x-www-form-urlencoded to make it work. Using the default form-data lead to the above mentioned error.
In my case, this was solved by changing the content-type as per http://developer.yodlee.com/Aggregation_API/Aggregation_Services_Guide/Aggregation_REST_API_Reference
require 'rest-client'
module Yodlee
def self.login_to_yodlee
site = self.site_resource
login_hash = {
cobrandLogin: 'yourlogin',
cobrandPassword: 'yourpassword'
}
begin
response = site["/authenticate/coblogin"].post login_hash, :'content-type' => 'application/x-www-form-urlencoded'
puts response
rescue RestClient::ResourceNotFound => ex
raise Exception.new(ex.response)
rescue Exception => ex
raise Exception.new(ex)
end
end
def self.site_resource
RestClient::Resource.new('https://rest.developer.yodlee.com/services/srest/restserver/v1.0')
end
end
Yodlee.login_to_yodlee
Generally, this error comes when you do not provide the input parameter's name correctly; while in this mentioned code above I could see that both of them are correct. I'd suggest you to please double check the input parameter name(case sensitive) as well properly. And just to mention you should be sending it as two different parameters i.e., 'cobrandLogin' and cobrandPassword.
Sinatra give me this error when I do a simple 'GET' request:
ERROR NoMethodError: undefined method `split' for nil:NilClass...
I think that the error is next to the Sinatra headers hash:
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = request.env["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]
and this is the get method:
get '/login' do
body(true.to_json)
end
What do you think?
I think you have posted incomplete error stacktrace. I suppose it may fail at true.to_json in case you are not loading required JSON library. Like
require 'json'
That error usually happens when the URL returns nil. Are you sure body(true.to_json) returns something?