Onelogin Logging a User In Via API not working - api

I'm using the onelogin REST api to log a user in: https://developers.onelogin.com/api-docs/1/samples/login-user-via-api.
I have followed all the steps successfully to generate a session token with no issues.
The documentation then says to post the session token to this url: https://admin.us.onelogin.com/session_via_api_token
However, when do the post to that URL with the session token it simply re-directs me to the onelogin Sign On Page.
Here is the c# code for the post. I have a valid session token in variable: session_token:
string url = "https://admin.us.onelogin.com/session_via_api_token";
StringBuilder postData = new StringBuilder();
postData.Append("session_token=" + HttpUtility.UrlEncode(session_token) + "&");
postData.Append("auth_token=" + HttpUtility.UrlEncode(""));
//ETC for all Form Elements
// Now to Send Data.
StreamWriter writer = null;
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.ToString().Length;
try
{
writer = new StreamWriter(request.GetRequestStream());
writer.Write(postData.ToString());
}
finally
{
if (writer != null)
writer.Close();
}

This appears to be server side code so this will never be able to successfully get a session with the end-user's browser.
In order for this flow to work properly, you need to redirect the end-user's browser to the https://admin.us.onelogin.com/session_via_api_token URL with just the auth_token value as a POST parameter.
All the above code will do is allow your back end server to get a session cookie, which doesn't help your end-user establish a session at all.
More details can be found here: https://developers.onelogin.com/api-docs/1/samples/login-user-via-api

Related

NTLM Auth with RestSharp

I am attempting to create some tests using RestSharp for a project I am working on.
This project uses Single Sign-on NTLM Authentication.
I am attemping to use a NTLMAuthenticator but my getUser request is always failing. I am not positive what URL to put in for the CredentialCache, the project or the SSO Id Provider.
SharedRequests shared = new SharedRequests();
var credential = new CredentialCache
{
{
new Uri("project or ID Provider URL or something else?"),
"NTLM",
new NetworkCredential("doamin\Username", "Password")
}
};
RestClient client = new RestClient();
client.BaseUrl=new Uri("projectURL");
client.Authenticator = new NtlmAuthenticator(credential);
client.PreAuthenticate = true;
RestRequest request = shared.GetCurrentUser();
IRestResponse response = client.Execute(request);
my response always gets a 500 error which is what is expected when no auth cookies are present.

JIRA - pass credentials for a webrequest to API?

Trying to build a service that will grab info on a JIRA ticket based on an ID passed to it.
I'm calling the API to take the ID passed to the service, tack it onto the URL for the API and get the JSON object.
Problem is, it appears one must be logged on or registered on JIRA in order to use the API.
So if I use the code below to make my request, I get a 404 error, as I do on any browser which I've not used to log onto Jira
public string Get(string id)
{
string html = string.Empty;
string url = #"https://company.atlassian.net/rest/api/latest/issue/" + id;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
return html;
}
I can add credentials to the request like so
request.Credentials = new NetworkCredential("vinnie#company.com","mypassword");
but I've no idea exactly what needs sending. I've tried the email address with which I'm set up in Jira but that doesn't work.
I have a suspicion that Jira adds a cookie to my browser which it uses to validate after the initial config - is that so? If so, what can I add/include on my web request to get it to run?
Am I just wildly off on the right way to access it? Or are there changes that can be made to the Jira side to allow requests?
You have to encode your credentials in Base64 format first and then these credentials can be put into your request as shown below:
string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
string base64Credentials = Convert.ToBase64String(byteCredentials);
request.Headers.Add("Authorization", "Basic " + base64Credentials);
Hope you're able to solve your problem by this approach!

Youtrack and RestSharp Permissions issue

I'm trying to create a youtrack client using RestSharp. I can log in, but when I try to get a project, I receive the following response:
{"value":"You do not have permissions to read project. You are logged in as ****"}
However, when I log into YouTrack on my browser, I can access the project and make changes, etc. Attached is my code (I am using RestSharp):
var client = new RestClient(Site);
var request = new RestRequest(String.Format("rest/user/login?login={0}&password={1}", Username, Password), Method.POST);
//reuse the client
client.CookieContainer = new System.Net.CookieContainer();
IRestResponse response = client.Execute(request);
var content = response.Content;
//returns <login>ok</login> - so it's logging in
Console.WriteLine("LOGIN \n" + content);
String projectId = "PW";
request = new RestRequest(String.Format("rest/admin/project/projectId={0}", projectId), Method.GET);
response = client.Execute(request);
content = response.Content;
Console.WriteLine("Get Project: \n\n" + content);
Is there something in the code I'm missing? Or is this a YouTrack setup issue that I need to take up with my administrator?
For future reference:
I do not have permissions for the /rest/admin resources, but I do have them for /rest/issue. These permissions can be set by the system administrator, if they check the "Groups" in their dashboard.

How to request for the crumb issuer for Jenkins

I want to use the Jenkins Remote API, and I am looking for safe solution. I came across Prevent Cross Site Request Forgery exploits and I want to use it, but I read somewhere that you have to make a crumb request.
How do I get a crumb request in order to get the API working?
I found this https://github.com/entagen/jenkins-build-per-branch/pull/20, but still I don't know how to fix it.
My Jenkins version is 1.50.x.
Authenticated remote API request responds with 403 when using POST request
I haven't found this in the documentation either. This code is tested against an older Jenkins (1.466), but should still work.
To issue the crumb use the crumbIssuer
// left out: you need to authenticate with user & password -> sample below
HttpGet httpGet = new HttpGet(jenkinsUrl + "crumbIssuer/api/json");
String crumbResponse = toString(httpclient, httpGet);
CrumbJson crumbJson = new Gson().fromJson(crumbResponse, CrumbJson.class);
This will get you a response like this
{"crumb":"fb171d526b9cc9e25afe80b356e12cb7","crumbRequestField":".crumb"}
This contains two pieces of information you need
the field name with which you need to pass the crumb
the crumb itself
If you now want to fetch something from Jenkins, add the crumb as header. In the sample below I fetch the latest build results.
HttpPost httpost = new HttpPost(jenkinsUrl + "rssLatest");
httpost.addHeader(crumbJson.crumbRequestField, crumbJson.crumb);
Here is the sample code as a whole. I am using gson 2.2.4 to parse the response and Apache's httpclient 4.2.3 for the rest.
import org.apache.http.auth.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import com.google.gson.Gson;
public class JenkinsMonitor {
public static void main(String[] args) throws Exception {
String protocol = "http";
String host = "your-jenkins-host.com";
int port = 8080;
String usernName = "username";
String password = "passwort";
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(usernName, password));
String jenkinsUrl = protocol + "://" + host + ":" + port + "/jenkins/";
try {
// get the crumb from Jenkins
// do this only once per HTTP session
// keep the crumb for every coming request
System.out.println("... issue crumb");
HttpGet httpGet = new HttpGet(jenkinsUrl + "crumbIssuer/api/json");
String crumbResponse= toString(httpclient, httpGet);
CrumbJson crumbJson = new Gson()
.fromJson(crumbResponse, CrumbJson.class);
// add the issued crumb to each request header
// the header field name is also contained in the json response
System.out.println("... issue rss of latest builds");
HttpPost httpost = new HttpPost(jenkinsUrl + "rssLatest");
httpost.addHeader(crumbJson.crumbRequestField, crumbJson.crumb);
toString(httpclient, httpost);
} finally {
httpclient.getConnectionManager().shutdown();
}
}
// helper construct to deserialize crumb json into
public static class CrumbJson {
public String crumb;
public String crumbRequestField;
}
private static String toString(DefaultHttpClient client,
HttpRequestBase request) throws Exception {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = client.execute(request, responseHandler);
System.out.println(responseBody + "\n");
return responseBody;
}
}
Or you can use Python and requests instead
req = requests.get('http://JENKINS_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)', auth=(username, password))
print(req.text)
will give you the name and the crumb:
Jenkins-Crumb:e2e41f670dc128f378b2a010b4fcb493
This Python function gets the crumb, and additionally uses the crumb to post to a Jenkins endpoint. This is tested with Jenkins 2.46.3 with CSRF protection turned on:
import urllib.parse
import requests
def build_jenkins_job(url, username, password):
"""Post to the specified Jenkins URL.
`username` is a valid user, and `password` is the user's password or
(preferably) hex API token.
"""
# Build the Jenkins crumb issuer URL
parsed_url = urllib.parse.urlparse(url)
crumb_issuer_url = urllib.parse.urlunparse((parsed_url.scheme,
parsed_url.netloc,
'crumbIssuer/api/json',
'', '', ''))
# Use the same session for all requests
session = requests.session()
# GET the Jenkins crumb
auth = requests.auth.HTTPBasicAuth(username, password)
r = session.get(crumb_issuer_url, auth=auth)
json = r.json()
crumb = {json['crumbRequestField']: json['crumb']}
# POST to the specified URL
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
headers.update(crumb)
r = session.post(url, headers=headers, auth=auth)
username = 'jenkins'
password = '3905697dd052ad99661d9e9f01d4c045'
url = 'http://jenkins.example.com/job/sample/build'
build_jenkins_job(url, username, password)
Meanwhile you can generate an API token in order to prevent having to include your password in the source code provided by the solutions above:
https://wiki.jenkins.io/display/JENKINS/Authenticating+scripted+clients
Refer - https://support.cloudbees.com/hc/en-us/articles/219257077-CSRF-Protection-Explained
If you authenticate with a username and a user API token then a crumb is not needed from Jenkins 2.96 weekly/2.107 LTS. For more information please refer to CSRF crumb no longer required when authenticating using API token or JENKINS-22474.
User cheffe's answer helped 90%. Thanks for giving us the right direction.
The missing 10% revolved around HTTP username and password authentication.
Since the Codenameone Java API I was using did not have the Authentication Class,
new UsernamePasswordCredentials(usernName, password));
I used:
String apiKey = "yourJenkinsUsername:yourJenkinsPassword";
httpConnection.addRequestHeader("Authorization", "Basic " + Base64.encode(apiKey.getBytes()));
User cheffe's Java snippet worked great for me on Jenkins v2.89.3 (Eclipse.org) and another Jenkins instance I use, at v2.60.3 (once enabled1).
I've added this to a Maven mojo2 I use for pushing locally-edited config.xml changes back to the server.
1 CSRF Protection
2 Hudson job sync plugin
In any of these answers I didn't find an option to use Jenkins API token.
I really tried all of these options but if you're enabling CSRF protection, you should access Jenkins APIs with Jenkins API token instead of normal password.
This token can be generated by each individual user in the user config page.
The token can be used as follows-
JenkinsApi::Client.new(server_url: jenkins_url, username: jenkins_user, password: jenkins_token)
P.S. - This initialization is for a Ruby Jenkins API client

Sitecore context & HttpWebRequest

Is it possible to pass Sitecore Credentials via an HttpWebRequest? The code below works great, except for the fact that the asmx being called executes as the anonymous user. I'd like to be able to pass the sitecore current user credentials to the page I'm calling.
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("ttp://localhost/file.asmx");
req.Headers.Add("SOAPAction", "\"h_ttp://tempuri.org/Register\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
req.ContentLength = 0;
req.CookieContainer = cookieJar;
WebResponse response = req.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader respStrm = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);
string responseITem = respStrm.ReadToEnd();
HttpContext.Current.Response.Write(responseITem);
HttpContext.Current.Response.End();
The Sitecore user credential informations are stored in a cookie. So you could add client cookies to your http request:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = new CookieContainer();
HttpCookieCollection userCookies = Request.Cookies;
for (int userCookieCount = 0; userCookieCount < userCookies.Count; userCookieCount++)
{
HttpCookie httpCookie = userCookies.Get(userCookieCount);
Cookie cookie = new Cookie();
/* We have to add the target host because the cookie does not contain the domain information.
In this case, this behaviour is not a security issue, because the target is our own platform.
Further informations: http://stackoverflow.com/a/460990
*/
cookie.Domain = request.RequestUri.Host;
cookie.Expires = httpCookie.Expires;
cookie.Name = httpCookie.Name;
cookie.Path = httpCookie.Path;
cookie.Secure = httpCookie.Secure;
cookie.Value = httpCookie.Value;
request.CookieContainer.Add(cookie);
}
You could also check our Sitecore Error Manager module. There we also create http requests with sending the client cookies (see lines 149-170):
https://github.com/unic/SitecoreErrorManager/blob/master/Modules.ErrorManager/Controls/BaseError.cs
You need to add the current user credentials to the request so you can retrieve them in your asmx webservice and use the credentials to log the user so the context is set.
// add the credentials to the Post method
var credentials = "yourCredentials";
req.ContentLength = credentials.Length;
using (var dataStream = req.GetRequestStream())
{
dataStream.Write(credentials, 0, credentials.Length);
}
In your asmx webservice you can login with the userName only or the combination of the userName and Password which are retrieved from the request.
Sitecore.Security.Authentication.AuthenticationManager.Login(userName);
EDIT: there is a security risk here when sending credentials as plain text, use at least HTTPS to make it more secure.