I am attempting to automate some tasks on my router. In order to do this a login is required to get a value called 'stok'. This value is returned as a cookie from the authentication request.
This is an example of the cookie captured in browser developer tools:
Set-Cookie: sysauth=34b2202d165b4316eb87c621df0ae0c9; path=/cgi-bin/luci/;stok=3ced8f80e529c0a378d79e279abfc456
The code snippet below is my attempt to log in. The problem is that the the cookieValue being returned is '34b2202d165b4316eb87c621df0ae0c9' as a string. The value that I need is the value identified as 'stok'.
let authResponse = Http.Request("http://192.168.1.2/cgi-bin/luci",
body = FormValues [ "username", username;
"password", password ])
let cookieValue = match authResponse.Cookies.TryFind("sysauth") with
| Some x -> x
| None _ -> ""
I cannot find any method to get at the 'path' and 'stok' values in the cookie. What am I missing?
Once you have the cookieValue, it should be an HttpCookie instance. And HttpCookie has a Values property that "Gets a collection of key/value pairs that are contained within a single cookie object."
I suspect that cookieValue.Values.["stok"] will contain the token you're looking for. If not, try looking through cookieValue.Values.AllKeys and see what it contains.
Related
My development Environment : eclipse java
I would like test a requestJWTuserToken sample, but I'm getting an error.
Test code:
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, userId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
Error message:
com.docusign.esign.client.ApiException: Error while requesting an access token:
class OAuthToken {
accessToken: null
tokenType: null
refreshToken: null
expiresIn: 0
at com.docusign.esign.client.ApiClient.requestJWTUserToken(ApiClient.java:719)
at smartsuite.app.util.DocuSignUtil.settingAuthentication(DocuSignUtil.java:112)
what are userid?
I found a admin sendbox at user > API username
enter image description here
This error is sometimes encountered when there is a problem with the RSA private key that you are using in your JWT request. Start by verifying how you are passing your key's private data into the request, if you are reading from a environment variable for example make sure the key's value is contained on a single line, otherwise it might be getting truncated.
If your key spans multiple lines as an environment variable try doing a regular expression find/replace where you replace all newline \n characters with the string literal "\n" and then pass that through to see if it resolves your issue.
I am using Silhouette security library. My Play server seem to send empty Session information in response. What am I doing wrong?
Following is the print on Play's console just before sending response.
Session(Map(authenticator -> 1-jtwBvA+LsLKE2rnkT/nMH1aQF9xc1twhECrma9mj3NUhUdVDmh/4wxQ2MxDOjcxkvEMTi1k63Dg5ezl+9FzDE3miaM5DbOrhyqAyGu4+30mHHV3QdPKA3IQQx5UdL1Hu85fZRI4f3Ef+q6xAgboDps0uBob5ojzo5Oqy8FNsoexn7Wr9iRyTr5xrMrLvl9GNQa+rA3q8qvW84sJaSei2iydrP2OjUbnnzo+zgrHLB3Bn7KJxOcFH4h9CikZNk/FHbtDm4uxzcK3paK1CuuIWLE8yvcYdavJ+4ejV5IaJ8QesJQRFgBktD9L/A2bc03eaA8wm)))
But in the the browser window, I notice that the value is empty.
Set-Cookie: PLAY_SESSION=; Max-Age=-86400;
Note that my browser earlier already had a PLAY_SESSION cookie from previous test runs. However, I would expect that the client application (Angular) would override old cookies with new cookies. Am I correct?
Following is the code snippet which creates, initialised and embed session information
val AuthenticatorFuture: Future[SessionAuthenticator] = silhouette.env.authenticatorService.create(loginInfo) //create authenticator
AuthenticatorFuture.flatMap(authenticator => { //got the authenticator
val securityTokenFuture: Future[Session] = silhouette.env.authenticatorService.init(authenticator) //init authenticator
securityTokenFuture.flatMap(securityToken=> {
println("adding security token: ",securityToken)
val result:Future[AuthenticatorResult] = silhouette.env.authenticatorService.embed(securityToken, Ok(Json.toJson(JsonResultSuccess("found user"))))
result
The Environment is defined as
trait SessionEnv extends Env {
type I = User
type A = SessionAuthenticator
}
As is passed to my controller as
silhouette: Silhouette[SessionEnv]
I created is at compile time as follows
val configSession = SessionAuthenticatorSettings()
val sessionAuthenticatorService = new SessionAuthenticatorService(configSession,fingerprintGenerator,authenticatorEncoder,new DefaultSessionCookieBaker(),clock)
val sessionEnv = com.mohiva.play.silhouette.api.Environment[SessionEnv](userIdentityService,sessionAuthenticatorService,Seq(),EventBus())
The issue is probably expected behavior of Play Framework as Silhouette doesn't modify the session cookie. I noticed that the browser already had a previous expired cookie and it sends it in the signin request. When Silhouette authenticator sees the expired cookie, it sends an empty value back. I think this is to make the browser discard the previous cookie.
I cannot figure out how to pass a redirect url to accomplish OAuth2 authorization. Google REST API indicates that redirect_url parameters can be passed but this .Net API does not seem to have a feature to pass redirect url
Dim Coll As New List(Of String)
Coll.Add(CalendarService.Scope.Calendar)
Coll.Add(Google.Apis.Tasks.v1.TasksService.Scope.Tasks)
Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With { _
.ClientId = ClientCredentials.ClientID, _
.ClientSecret = ClientCredentials.ClientSecret _
}, Coll, "user", CancellationToken.None, New SavedDataStore(myStoredResponse)).Result
Dim CalService = New CalendarService(New BaseClientService.Initializer() With { _
.HttpClientInitializer = credential, _
.ApplicationName = "myApp"})
A browser instance is launched when this code is executed but the return_url parameter in that request is always to to some random url (e.g., http://localhost:<random port number>/Authorize. Don't know where is this value coming from. In the API console, I have set http://localhost:4444/Home/Index. Since there is no match, authentication throws Error: redirect_uri_mismatch
The above code results into this request url
https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=589627125301.apps.googleusercontent.com&redirect_uri=http://localhost:44933/authorize/&scope=https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/tasks
In summary the question is, where is this http://localhost:44933/authorize/ coming from?
Any pointers as to how to set this redirect_uri parameter in the code?
Try adding a .CallbackURL property. Google API usually looks for one.
I am making the following request which is returning Json.
let baseUrl = "http://wex-qa.mybluemix.net/resources/question"
let userName = "yourName#aol.com"
let password = "yourCreds"
let authKey = userName + ":" + password
let client = new HttpClient()
client.DefaultRequestHeaders.Authorization <- new AuthenticationHeaderValue("Basic",authKey)
let input = new Dictionary<string,string>()
input.Add("question","what time is it")
let content = new FormUrlEncodedContent(input)
let result = client.PostAsync(baseUrl,content).Result
let resultContent = result.Content.ReadAsStringAsync().Result
I immediately thought of using the Json Type Provider so I made a local file of the response to be the type def. I then went to load the type where I need the credentials and the content. However, I did not see where the .Load() function have an overload to pass in the credentials and the content. Should I continue to make the request via the HttpClient class and use the .Parse() function?
Thanks in advance.
Expanding on the answer in the comments (which is correct).
I had this problem in 2022 with FSharp.Data 4.2.9. There still seems to be no way to put authorisation credentials into the requests for either defining the JsonProvider type, or the runtime collection of data. With a bit of working around, it can be made to work like a type provider, as described in the question and comment.
Get your credentials for web requests from the site. This often involves a single 'key' rather than a username/password pair.
Instantiate the type provider with sample data from the site (extracted with the required credentials).
At runtime, use HttpClient with Authorization, to read JSON from the URL, and then use the Parse method of the type provide to return typed data. This allows you to use intellisense on the returned data
This example is for the MailChimp API, which supports mailing lists and requires a company API Key on web requests.
First, follow instructions on the site to get 'Credentials' for API calls.
Second, use any method to extract sample JSON to a file. I used the PHP samples provided by MailChimp.
Then define the JsonProvider with that data.
type mcListsTypeProvider = JsonProvider< "./lists_sample_data.json">
Here lists is a fundamental component of the API. In this example, I will be working with the "Sales Subscribers" list.
The next function will read from a URL, and return typed Json data, as if directly from the Load function.
The core of this is the jsonProviderParse argument, which is the Parse method from the JsonProvider.
let loadTypedJson url jsonProviderParse =
use httpClient = new HttpClient()
// Set up authorisation
let mailChimpApiKey = "3ef8dXXXXXXXXXXXXXXXXf61e-us18" // Could be a "userName:passowrd" key
httpClient.DefaultRequestHeaders.Authorization <- AuthenticationHeaderValue("Basic",mailChimpApiKey)
// Get content
let result = httpClient.GetAsync(url : string).Result
let content = result.Content.ReadAsStringAsync().Result
// Parse content, with the Parse method from the JsonProvider
jsonProviderParse content
Then use loadTypedJson as you would myTypeProvider.Load("https:..")
// Find the MailChimp list Id for the "Sales Subscribers" list
let listsUrl = "https://us18.api.mailchimp.com/3.0/lists"
let data = loadTypedJson listsUrl mcListsTypeProvider.Parse
let list_id =
data.Lists
|> Seq.find (fun list -> list.Name = "Sale Subscribers")
|> (fun x -> x.Id)
printfn "Sale Subscribers list_id = %s" list_id
Output: list_id = f21XXXXX85
Intellisense working for the JsonProvider
I have successively obtained a request token, and am now using it in conjunction with my consumer key to create the following request
https://us.etrade.com/e/etws/authorize?key=2fc*******c323d6&token=IIrs6BsIrGQ********duC60GAmLq8
where the asterisks have been substituted for my consumer key and request token. I give this as an argument to getAuthorizeURL This returns an ETWSException and output in the terminal reading
ERROR OAuthClientImpl - Mandatory parameters missing
I have the two required arguments for the getAuthorizeURL method, and I am sure they are formatted correctly. Can anyone tell me what is going wrong here?
Also, if it helps to know, calling the getAuthorizeURL causes my default browser to open and brings me to the address that I entered above, but it returns a 404 error.
If you're using the sample code from the Docs.. they are missing 1 piece.
(java)
client = OAuthClientImpl.getInstance(); // Instantiate IOAUthClient
request = new ClientRequest(); // Instantiate ClientRequest
request.setEnv(Environment.SANDBOX); // Use sandbox environment
request.setConsumerKey(oauth_consumer_key); //Set consumer key
request.setConsumerSecret(oauth_consumer_secret); // Set consumer secret
token= client.getRequestToken(request); // Get request-token object
oauth_request_token = token.getToken(); // Get token string
oauth_request_token_secret = token.getSecret(); // Get token secret
request.setToken(oauth_request_token);
request.setTokenSecret(oauth_request_token_secret);
String authorizeURL = null;
authorizeURL = client.getAuthorizeUrl(request);
URI uri = new URI(authorizeURL);
Desktop desktop = Desktop.getDesktop();
desktop.browse(uri);
The Documentation sample forgot to mention, you'll need to set the Token Key/Secret on the Request object, before you make the call the get AuthorizeUri.
request.setToken(oauth_request_token);
request.setTokenSecret(oauth_request_token_secret);