I would like to set my token only once per user, do you know how to check if my token is already set ?
Here is my Controller :
def connexion
code = request.params[:code]
#decoded_code = URI.decode(code)
#id_connection = request.params[:id_connection]
#token = HTTParty.post('https://test-sandbox/auth/token/access',
body: {
client_id: XXXXXX,
client_secret: "YYYYYYYYYYYYYYYYY",
code: #decoded_code
}
)
end
If I go back to my page and re-set the token I have the following error : You have already got an access_token for this user
You can use ||= operator to set token, if it is not set than it will try to get token
#token ||= HTTParty.post('https://test-sandbox/auth/token/access',
body: {
client_id: XXXXXX,
client_secret: "YYYYYYYYYYYYYYYYY",
code: #decoded_code
}
)
Related
I wrote an API using django and djano-ninja.
Here is my section of api.py file which is imported to URL.
class ORJSONRenderer(BaseRenderer):
media_type = "application/json"
def render(self, request, data, *, response_status):
return orjson.dumps(data)
class ApiKey(APIKeyQuery):
param_name = "api_key"
def authenticate(self, request, key):
try:
return CustomUser.objects.get(api_key=key)
except CustomUser.DoesNotExist:
pass
api_key = ApiKey()
api = NinjaAPI(
title="Good TExt",
version="0.0.1",
description="That This",
renderer=ORJSONRenderer(),
# csrf=True
)
#api.patch(
"/car/color/{new_color}", auth=api_key, tags=["Car"], summary="Does something",
description="Does something"
)
def update_team_name(request, new_color):
try:
#Do something
msg = {"success": "Done"}
except:
msg = {"error": "Problem"}
return HttpResponse(json.dumps(msg), content_type='application/json')
I have other get endpoints too. There is no problem when I request get endpoints.
But when I send a request to patch endpoints I am getting 401 (Unauthorized) only with ajax. I mean python's requests work.
import requests
load = dict(
api_key='SOME HEY'
)
r = requests.get("http://127.0.0.1:8000/api/car/color/red", params=load)
print(r.text)
But javascript doesn't:
$.ajax({
url: "/api/car/color/red",
data: {
"api_key": "some key"
},
cache: false,
type: "PATCH",
success: function(response_country) {
console.log(response_country);
},
error: function(xhr) {
console.log(xhr);
}
});
What I did try
I tried to add:
headers:{"X-CSRFToken": $crf_token},
to header of the ajax request. Even though csrf is set to False in django-ninja
I tried to change from PATCH to PUT
I tried to add a timeout to ajax request
I tried to send the api_key trough header and not the data
with no success.
I'm new to Ruby and I'm trying to implement a oauth2 with client credentials flow.
I've found the "ouath2" gem, but that requires a redirect_uri that I don't have.
Here is the gem.
Here is what I'm trying to implement
secret_id = 'this-is-a-secret-id'
token_id = 'this-is-a-token-id'
scope = 'such-a-good-scope'
grant_type = 'client_credentials'
#client = nil
# Get access token
def GetAccessToken
HttpRequest request = HttpRequest::Post("https://awesome-page.com/oauth/token")
request.content = {
{ "client_id" => token_id },
{ "client_secret" => secret_id }
{ 'grant_type' => grant_type },
{ 'scope' => scope}
}
response = request.send
json = response.content
accessToken = JsonConvert.DeserializeObject<Token>(json)
#client = Client.new(bearer: accessToken)
end
# Refresh token
def RefreshToken
HttpRequest request = HttpRequest::Post("https://awesome-page.com/oauth/token")
request.content = {
{ "client_id" => token_id },
{ "client_secret" => secret_id }
{ 'grant_type' => grant_type },
{ 'refresh_token' => scope}
}
response = request.send
json = response.content
accessToken = JsonConvert.DeserializeObject<Token>(json)
#client = Client.new(bearer: accessToken)
end
# End then implementing the "getting the resources with the client" part and so on...
Any idea how to do this, I'm getting a little bit desperate now
Any help is greatly appreciated!
You’re kind of going about this all wrong. With the Oauth2 gem you need to:
Initialise a new Oauth2::Client with your client ID, secret, scope, and define the token and redirect url (this is a url in your app that users logging in get sent back to. Not used for Client Credentials flow as it’s for server to server comms)
Call token = client.client_credentials.get_token. This sets token to an AccessToken it obtained.
Then call token.get(‘https://your-url.com/path/to/resource’) - or post/patch/delete.
Look at the access_token.rb file in the repo to see the methods you can call. They also take a series of params, for things like additional headers or body payload you can pass. It’s based on Faraday so you can always look up Faraday docs for help with that part.
Endpoint: https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps
Error:
RuntimeError - {"error"=>{"code"=>"BadRequest", "message"=>"Request not applicable to target tenant.", "innerError"=>{"request-id"=>"476e2f7d-e539-4b93-82c1-45be7e0b183b", "date"=>"2019-07-18T08:21:53"}}}
I am trying to fetch all apps from my Microsoft account but I got a runtime exception. Using the same approach I am Successful to fetch all users.
def admin_authorize
client = Signet::OAuth2::Client.new(
authorization_uri: 'https://login.microsoftonline.com/51f6420c-47a1-4701-8bf9-e5b71795f17a/adminconsent',
client_id: CLIENT,
redirect_uri: 'http://localhost:3000/integrations/microsoft/oauth2callback',
state: '12345678900'
)
redirect_to client.authorization_uri.to_s
end
def authorize_callback
if params[:admin_consent] == "True"
response = token
#users response.parsed_response["access_token"]
apps response.parsed_response["access_token"]
else
redirect_to 'http://test-company.localhost:3000/dashboard'
end
end
def token
body = {
grant_type: 'client_credentials',
client_id: CLIENT,
client_secret: SECRET,
scope: 'https://graph.microsoft.com/.default',
redirect_uri: 'http://localhost:3000/integrations/microsoft/oauth2callback',
}
headers = {'Content-Type': "application/x-www-form-urlencoded"}
response = HTTParty.post "https://login.microsoftonline.com/#{TENANT}/oauth2/v2.0/token", headers: headers, body: body
end
def users access_token
url = '/v1.0/users'
response = make_api_call url, access_token
raise response.parsed_response.to_s || "Request returned #{response.code}" unless response.code == 200
response.parsed_response['value']
end
def apps access_token
url = '/v1.0/deviceAppManagement/mobileApps'
response = make_api_call url, access_token
raise response.parsed_response.to_s || "Request returned #{response.code}" unless response.code == 200
response.parsed_response['value']
end
def make_api_call(endpoint, token, params = nil)
headers = {
Authorization: "Bearer #{token}",
'Content-Type': 'application/json'
}
query = params || {}
HTTParty.get "#{GRAPH_HOST}#{endpoint}",
headers: headers,
query: query
end
All Intune Graph APIs require Azure AD Premium P2 version. If you enable Azure AD Premium P2 then it will give output.
I have this basic piece of code which doesn't work properly.
If I run the following I get:
".rvm/gems/ruby-1.9.3-p484/gems/multi_xml-0.5.5/lib/multi_xml/parsers/rexml.rb:18:in `parse': The document "The supplied authentication is invalid" does not have a valid root (MultiXml::ParseError)"
class Temp
include HTTParty
format :xml
def initialize()
self.class.base_uri "https://beta2014.vchs.vmware.com"
end
def login(username, password)
self.class.basic_auth username, password
self.class.default_options[:headers] = {"Accept" => "application/xml;version=5.7"}
response = self.class.post('/api/iam/login')
# setting global cookie var to be used later on
#cookie = response.headers['vchs-authorization']
return #cookie
end
def plans(token)
token = 'Bearer ' + token
self.class.base_uri "https://beta2014.vchs.vmware.com"
self.class.default_options[:headers] = { 'Accept' => "application/xml;class=com.vmware.vchs.iam.api.schema.v2.classes.user.Users;version=5.7", 'Authorization' => token }
response = self.class.get('/api/sc/plans')
end
end #class Temp
temp = Temp.new()
token = temp.login(username, password)
temp.plans(token)
The token has the right content. I know that because if I "puts" the value of the token and copy&paste it into a REST client it works just fine.
Interestingly enough, if I generate the token on the REST client and I statically set the token with token = <string> (instead of calling temp.login) the call temp.plans works just fine and I get my proper response.
I have also tried to do:
tokendummy = temp.login(username, password)
token = <string>
and it fails again.
It's like if token.plans works only if it's the first method being called. If it's the second (after temp.login) it fails.
Does it have something to do with the initialize() method that is only being called the first time?
I've got a Sinatra/Warden Remote API, and a client in RubyMotion.
How can I post the Authentication Token and User Object with AFMotion for initial registration (from client)?
This more or less what I have so far, not much I know.
Basically I need to pass through a token to the remote api and a user object.
def register_user(user)
#client = AFMotion::Client.build("http://localhost:9393/register") do
header "Accept", "application/json"
request_serializer: :json
response_serializer :json
end
end
Help?
You can change the line you initiate #client object to something like this
#client = AFMotion::Client.build("http://localhost:9393/") do
header "Accept", "application/json"
response_serializer :json
end
and when you want to do a POST request, you can do
#client.post('register', {
token: 'TOKEN HERE',
user: 'USER OBJECT HERE'
}) do |result|
puts result
end
You can find out more here.