The docs make no mention of pin-authentication that I can see. (No search results)
Is it possible using sanction?
Yes it is:
client_pin = ''
client_id = 'your_client_id'
client_secret = 'your_client_secret'
request_token = 'some_random_state_hash'
client_pin = input('Enter PIN:')
access_token_url = 'https://api.home.nest.com/oauth2/access_token'
c = Client(
token_endpoint=access_token_url_plain,
client_id=client_id,
client_secret=client_secret)
c.request_token(code = client_pin)
You should now have a session.
Related
import random
import urllib.parse as urllibparse
import spotipy
from spotipy.oauth2 import SpotifyOAuth
# credentials
Client_Id = <CLIENT_ID>
Client_Secret = <CLIENT_SECRET>
redirect_uri = 'http://localhost:5500/'
scope = "playlist-modify-private playlist-modify-public"
response_type = 'code'
username = <USERNAME>
randomNum =str(random.getrandbits(128))
hash = int(randomNum,36)
state = hex(hash)
spotifyToken = SpotifyOAuth(Client_Id,Client_Secret,redirect_uri,state,scope)
auth_url = spotifyToken.get_authorize_url()
print(auth_url)
spotifyObject = spotipy.Spotify(auth_manager=spotifyToken)
print(spotifyObject)
playlistName = "random"
playlistDescription = "just to check"
spotifyObject.user_playlist_create(user=username,name=playlistName,public=True,description=playlistDescription)
suggestions required
often redirected to login page rather than authorization page pls suggest some solution to resolve this problem or suggest any other way.
I am trying to retrieve the signed in user's name and email address once they have signed in via Google. Here is my code:
#app.route("/callback")
def callback():
flow.fetch_token(authorization_response=request.url)
if not session["state"] == request.args["state"]:
abort(500) # State does not match!
credentials = flow.credentials
request_session = requests.session()
cached_session = cachecontrol.CacheControl(request_session)
token_request = google.auth.transport.requests.Request(session=cached_session)
id_info = id_token.verify_oauth2_token(
id_token=credentials._id_token,
request=token_request,
audience=oauth_client_id
)
session["google_id"] = id_info.get("sub")
session["name"] = id_info.get("name")
session["email"] = id_info.get("email")
return redirect("/")
Nothing displays when I store session["name"] = id_info.get("name") or session["email"] = id_info.get("email") in a variable and print this to console?
I'm trying to use access tokens from #azure/identity to connect to azure sql using mssql (which uses tedious behind the scenes). The access tokens don't seem to work as is (quite similar to python - more on this later).
I have the following code:
const identity = require("#azure/identity")
function getConfig(accessToken){
var config = {
"authentication": {
"type": "azure-active-directory-access-token",
"options": {
"token": accessToken
}
},
"server": "dbserver.database.windows.net",
"options": {
"encrypt": true,
"database": "dbname",
}
};
return config;
}
const cred = new identity.DefaultAzureCredential();
const token = await cred.getToken("https://database.windows.net/.default")
const conf = getConfig(token.token)
let pool = await sql.connect(conf)
This always fails with "Login failed for user ''".
I have the following python code which does exactly the same:
def get_token():
creds = identity.DefaultAzureCredential()
token = creds.get_token("https://database.windows.net/.default")
tokenb = bytes(token.token, "UTF-8")
exptoken = b''
for i in tokenb:
exptoken += bytes({i})
exptoken += bytes(1)
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken
return tokenstruct
def execute_query():
access_token = get_token()
print(access_token)
sql_server_name = "db-server"
sql_server_db = "database_name"
SQL_COPT_SS_ACCESS_TOKEN = 1256
connString = f"Driver={{ODBC Driver 17 for SQL Server}};SERVER={sql_server_name}.database.windows.net;DATABASE={sql_server_db}"
conn = pyodbc.connect(connString, attrs_before={
SQL_COPT_SS_ACCESS_TOKEN: access_token})
cursor = conn.cursor()
cursor.execute("SELECT * from SYSOBJECTS")
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
This works perfectly. I've also noticed the following:
If I take the access token from the node version (printed by console.log) and pass it to the python code in please of access_token, I get the same error from python (Login failed for user '').
If I pass the access token from javascript and pass it to the python code for token.token (in get_token), then it works perfectly.
So I'm guessing the binary padding and packing thing that's working for python needs to be done for the node code to work. Is there some way of doing this? Or is there some better way to pass an access token from azure-identity to tedious?
Doh... I was using node-mssql which is the abandoned 0.0.1 library. Switching to mssql (v6.3.1) uses a recent version of tedious, and the access token works directly.
I'm looking to get access_token from fyers API
I'm able to get authorization_code and build authorization_url to open it in browser to enter user credentials. access_token is displayed in browser's address when user enters credentials but my program is unable to retrieve the access_code.
Your help is much appreciable.
My code is as follows:
from fyers_api import accessToken
from fyers_api import fyersModel
import requests
import webbrowser
import urllib.request as ur
app_id = "XXXXXXXXX"
app_secret = "XXXXXXXXX"
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()
if response['code'] != 200:
print('CODE=' + str(response['code']))
print('MESSAGE=' + str(response['message']))
print('Exiting program...')
exit(0)
authorization_code = response['data']['authorization_code']
app_session.set_token(authorization_code)
authorization_url=app_session.generate_token('XXXXXX')
token = webbrowser.open(authorization_url)
#Following authorization url is opened in browser:
#https://api.fyers.in/api/v1/genrateToken?authorization_code=xxxxxxxxxxxxx&appId=xxxxxxxxx&user_id=xxxxxx
#User is redirected to following url after successful log-in:
#https://trade.fyers.in/?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=&user_id=xxxxxx
print(token)
#token=”your_access_token”
#is_async = False #(By default False, Change to True for asnyc API calls.)
#fyers = fyersModel.FyersModel(is_async)
#fyers. get_profile(token = token)
Instead of writing the mentioned code, it is better to directly call Fyers Api.
import requests
url = 'https://api.fyers.in/api/v1/token'
requestParams = {
"fyers_id":"Your Client ID",
"password":"Your Password",
"pan_dob":"Your PAN card or DOB(DD-MM-YYYY)",
"appId":"YOur APP ID",
"create_cookie":False}
response = requests.post(url, json = requestParams )
print (response.text)
from fyers_api import accessToken
from fyers_api import fyersModel
app_id = "xxxxxxxxxx"
app_secret = "xxxxxxxxxx"
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()
print(app_session)
print(response)
authorization_code = response['data']['authorization_code']
app_session.set_token(authorization_code)
gen_token = app_session.generate_token()
print("token url is copy paste this url in browser and copy access
token excluding your id at Last ")
print(gen_token)
print("tokent printed thanks")
token="gAAAAABeTWk7AnufuuQQx0D0NkgABinWk7AnufuuQQx0DQ3ctAFWk7AnufuuQQx0DMQQwacJ-
_xUVnrTu2Pk5K5QCLF0SZmw7nlpaWk7AnufuuQQx0DG4_3EGCYw92-iAh8="
is_async = False
fyers = fyersModel.FyersModel(is_async)
print(fyers. get_profile(token = token))
fyers.funds(token = token)
print(fyers.funds(token = token))
I'm trying to authenticate to a REST API using encryption.
First I need to call the API to get an encryptionKey and a timestamp.
The encryptionKey is in Base 64 format.
Then I need to create a RSAToken using the key and finaly encrypt the password using password + "|" + timestamp.
This is some sample code using python to authenticate to the API
key, timestamp = get_encryption_key()
decoded_key = key.decode('base64')
rsa_key = RSA.importKey(decoded_key)
encrypted = rsa_key.encrypt(password + '|' + str(timestamp), 'x')
encrypted_password = encrypted[0]
and
import base64
from Crypto.PublicKey import RSA
r = requests.get(my_url, headers=headers)
myData = r.json()
decoded = base64.b64decode(myData['encryptionKey'])
key = RSA.importKey(decoded)
enc = key.encrypt(password + '|' + str(myData['timeStamp']), 'x')
encryptedPassword = enc[0]
session = "/session"
my_url = url + session
payload = {"identifier": identifier,
"password": encryptedPassword,
"encryptedPassword": "True"
}
Any hints to achieve this under Node?
You can use crypto.publicEncrypt to encrypt your password. Notice the padding, you might want to use the right padding that is being used in your Python script.
const crypto = require('crypto');
const constants = require('constants');
const decodedKey = Buffer(encriptionKey, 'base64').toString();
const encryptedPassword = crypto.publicEncrypt({
key: decodedKey,
padding : constants.RSA_PKCS1_OAEP_PADDING
} , Buffer(`${password}|${timestamp}`));
Check out this node.js test to find out more examples for different padding.