I wrote some code that gets an access token. When the code runs, a browser displays on the screen which contains the access token.
But when I try to get the access token and log it, a null string is being displayed. Also, I do not know if there is a way to force the browser to close using my code. Right now when I run this code, the browser window opens but I have to click on it to close it.
Could you please let me know what I am doing wrong ?
import com.eviware.soapui.impl.rest.actions.oauth.OltuOAuth2ClientFacade
import com.eviware.soapui.support.editor.inspectors.auth.TokenType
def project = context.getTestCase().getTestSuite().getProject();
def oAuthProfile = project.getAuthRepository().getEntry("IMAGEN_Profile");
def clientSecret = testRunner.testCase.testSuite.getPropertyValue("Client_Secret")
def clientID = testRunner.testCase.testSuite.getPropertyValue("Client_ID")
oAuthProfile.setClientSecret(clientSecret);
oAuthProfile.setClientID(clientID);
log.info("Client Secret:"+clientSecret)
log.info("Client ID:"+clientID)
// the following code for getting new access token
def oAuthClientFacade = new OltuOAuth2ClientFacade(TokenType.ACCESS);
oAuthClientFacade.requestAccessToken(oAuthProfile, true);
def accessToken = oAuthProfile.getAccessToken()
testRunner.testCase.testSuite.setPropertyValue("Auth_Code",accessToken)
log.info("Access Token:"+accessToken)
Unfortunately, the SoapUI documentation is rather terse.
Change your
oAuthClientFacade.requestAccessToken(oAuthProfile, true);
to
oAuthClientFacade.requestAccessToken(oAuthProfile, true, true);
source
Related
from msal import PublicClientApplication
TENANT_ID = '********-bca4-4be6-8a1d-********'
CLIENT_ID = '********-2f0b-4b9c-84ed-*******'
AUTHORITY = 'https://login.microsoftonline.com/consumers'
ENDPOINT = 'https://graph.microsoft.com/v1.0'
SCOPES = [
'Files.ReadWrite',
'Files.ReadWrite.All',
'Sites.ReadWrite.All',
'User.Read',
'User.ReadBasic.All',
'User.ReadWrite'
]
app = PublicClientApplication(CLIENT_ID, authority=AUTHORITY)
flow = app.initiate_device_flow(scopes=SCOPES)
print(flow)
if 'user_code' not in flow:
raise Exception('Failed to create device flow')
print(flow['message'])
result = app.acquire_token_by_device_flow(flow)
print(result)
print(flow) prints following data:
{'user_code': 'W57NE', 'device_code': 'SAQABAAEmX5eRRF9rmeBg4brEBmPRxtxI9LWyWTGPCHL6GEu7_PLvbhtOe9flSsOWYBPGifMtxiDU6gWx3n3qyNIc2MHmkghc74onQIzUzvQOJVXQgc5QH-wwjIAA', 'verification_uri': 'https://www.microsoft.com/link', 'expires_in': 900, 'interval': 5, 'message': 'To sign in, use a web browser to open the page https://www.microsoft.com/link and enter the code W57NE to authenticate.', 'expires_at': 1613721382.451286, '_correlation_id': 'ea1f9e06-39b1-47f5-bac0-e3d0188cabbd'}
I open the url in the browser and entered code mentioned in the response but it says The code that you entered has expired. Get a new code from the device you're trying to sign in to and try again.
Basically my use case is get access token using python script.
Thank you for help in advance.
I'm trying to get a POST requests through python. Server side dev provided me with an auth key ie: short124 and a long key. They were generated by Mohawk library. Dev from server side gave me a code example:
import requests
from mohawk import Sender
creds = {'id': short,'key':very_long_key,'algorithm':'sha256'}
auth_session = Sender( credentials = creds, url = url, method = 'POST',always_hash_content=False)
headers = {'Authorization' : auth_session.request_header}
r = requests.post(url,data = input, headers = headers, verify = False)
print(r)
Unfortunately I get 401 error (unauthorized) with the credentials provided,
Can anyone give me some advide?
The way it's being used seem correct. I would double check the credentials and the url.
Also consider using Black it will make code formatting a breeze.
I am successfully able to authorize my application with a 3rd party OAuth2 provider (Xero), but have been unable to refresh the token, either automatically, or manually.
The documentation suggests authlib can do this automatically. I have tried two different approaches from the Authlib documentation, on the flask client docs they give an example of "Auto Update Token via Signal", and on the web client docs they register an "update_token" function.
Using either approach, there is never an attempt made to refresh the token, the request is passed to Xero with the expired token, I receive an error, and the only way to continue is to manually re-authorize the application with Xero.
Here is the relevant code for the "update_token" method from the web client docs:
#this never ends up getting called.
def save_xero_token(name,token,refresh_token=None,access_token=None,tenant_id=None):
logging.info('Called save xero token.')
#removed irrelevant code that stores token in NDB here.
cache = Cache()
oauth = OAuth(app,cache=cache)
oauth.register(name='xero',
client_id = Meta.xero_consumer_client_id,
client_secret = Meta.xero_consumer_secret,
access_token_url = 'https://identity.xero.com/connect/token',
authorize_url = 'https://login.xero.com/identity/connect/authorize',
fetch_token = fetch_xero_token,
update_token = save_xero_token,
client_kwargs={'scope':' '.join(Meta.xero_oauth_scopes)},
)
xero_tenant_id = 'abcd-123-placeholder-for-stackoverflow'
url = 'https://api.xero.com/api.xro/2.0/Invoices/ABCD-123-PLACEHOLDER-FOR-STACKOVERFLOW'
headers = {'Xero-tenant-id':xero_tenant_id,'Accept':'application/json'}
response = oauth.xero.get(url,headers=headers) #works fine until token is expired.
I am storing my token in the following NDB model:
class OAuth2Token(ndb.Model):
name = ndb.StringProperty()
token_type = ndb.StringProperty()
access_token = ndb.StringProperty()
refresh_token = ndb.StringProperty()
expires_at = ndb.IntegerProperty()
xero_tenant_id = ndb.StringProperty()
def to_token(self):
return dict(
access_token=self.access_token,
token_type=self.token_type,
refresh_token=self.refresh_token,
expires_at=self.expires_at
)
For completeness, here's how I store the initial response from Xero (which works fine):
#app.route('/XeroOAuthRedirect')
def xeroOAuthLanding():
token = oauth.xero.authorize_access_token()
connections_response = oauth.xero.get('https://api.xero.com/connections')
connections = connections_response.json()
for tenant in connections:
print('saving first org, this app currently supports one xero org only.')
save_xero_token('xero',token,tenant_id=tenant['tenantId'])
return 'Authorized application with Xero'
How can I get automatic refreshing to work, and how can I manually trigger a refresh request when using the flask client, in the event automatic refreshing fails?
I believe I've found the problem here, and the root of it was the passing of a Cache (for temporary credential storage) when initializing OAuth:
cache = Cache()
oauth = OAuth(app,cache=cache)
When the cache is passed, it appears to preempt the update_token (and possibly fetch_token) parameters.
It should be simply:
oauth = OAuth(app)
oauth.register(name='xero',
client_id = Meta.xero_consumer_client_id,
client_secret = Meta.xero_consumer_secret,
access_token_url = 'https://identity.xero.com/connect/token',
authorize_url = 'https://login.xero.com/identity/connect/authorize',
fetch_token = fetch_xero_token,
update_token = save_xero_token,
client_kwargs={'scope':' '.join(Meta.xero_oauth_scopes)},
)
in addition, the parameters on my "save_xero_token" function needed to be adjusted to match the documentation, however this was not relevant to the original problem the question was addressing.
I need to write a script that is included in the personal account of my Internet provider and transmits information about the current balance.
At the moment I am stuck at the time of authorization. I found and edited such a script for myself:
import requests
url = 'https://bill.tomtel.ru/login.html'
USERNAME, PASSWORD, = 'mylogin', 'mypass'
resp = requests.get(url, auth=(USERNAME, PASSWORD))
r = requests.post(url)
print(r.content)
But this does not help to pass authorization...
I can enter this link through a browser and go to a page of this type:
https://bill.tomtel.ru/fastcom/!w3_p_main.showform?FORMNAME=QFRAME&CONFIG=CONTRACT&SID=BLABLABLA&NLS=WR
I can go through browser authorization through both links, but why can't I do this through a script?
Please help with this.
Your browser probably has a session token/cookie stored and that is why you can access it through the browser. There are a couple issues here:
It looks like you need to login to the site first -- through a POST method, not a GET. The GET is what loads the page. But once you submit the form it's going to do a POST request.
Actually, using requests to login to a site is not as easy as it looks. Usually you have to find the url it's posting to (examine the developer toolbar to see the url), and you often have to pass information in addition to your username/password, such as a csrf token, a cookie, or something else.
I would suggest using a browser-automator for this, perhaps something like selenium Webdriver. It makes logging into a site much simpler than using HTTP in a raw request, as it emulates a browser. I would suggest this -- it's much simpler and faster!
Another thing to note: auth=(USERNAME, PASSWORD) is not quite the username/password in the form (it's something else) but I don't think understanding that is too relevant to what you're trying to do.
Here is the url and required form data to log in:
I think you should try this:
import requests
url = 'https://bill.tomtel.ru/signin.php'
USERNAME = input('Enter your username: ')
PASSWORD = input('Enter your password: ')
d = {
'USERNAME' : USERNAME,
'PASSWORD' : PASSWORD,
'FORMNAME' : 'QFRAME'}
session = requests.Session()
resp = session.post(url, data=d).text
if not '<TITLE>' in resp:
print('Incorrect username or password!')
quit()
print('Logging in ... ')
for line in resp.split('\n'):
if 'location' in line:
red = 'https://bill.tomtel.ru/fastcom/!w3_p_main.showform%s' % line.replace(' if (P>0) self.location.replace("', '').replace('");', '')
if not red:
print('An error has occured')
quit()
print('Redirecting to %s' % red)
page = session.get(red).text
print('')
print(' MAIN PAGE')
print(page)
So I am trying to work on a groovy script within Jenkins that takes a file from local machine and pushes to a confluence page.
I can't seem to find any documentation for this.
I found this code, and I'm new to groovy so just wanted to make sure I'm on the correct track. I added some comments to my understanding if someone could clarify what they mean that would be awesome, and let me know if I am on the right track?
def server = new XMLRPCServerProxy("http://confluence:8090/rpc/xmlrpc")//Here we would have the link to our confluence server
def spaceKey = "Area" // not sure what spaceKey means
def pageTitel = "FileUpload"//The title of the page we are uploading to
def fileName = "D:\\datamodel.pdf"//the file path
def contentType = "application/pdf"//file extensions
def token = server.confluence2.login("UserName" , "Password")//confluence login credientials
def page = server.confluence2.getPage(token, spaceKey, pageTitel)//not sure
def file = new File (fileName)
server.confluence2.addAttachment( token, page.id, [ fileName: file.name, contentType:contentType ], file.bytes )
i'm work with the same task, but find only case with curl. It's work, but this is not groovy.