I am not able to authenticate in stripe.com - using Basic Authentication
public class Str extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw=response.getWriter();
pw.println("Hello World");
HttpClient client= new HttpClient();
String req="https://api.stripe.com/";
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(new AuthScope(req, 443, null), new UsernamePasswordCredentials("<api-key>"));
client.getHostConfiguration().setHost(req, 443, "https");
PostMethod post= new PostMethod("https://api.stripe.com/v1/charges/");
//post.addParameter("id", "<id>");
int status=client.executeMethod(post);
pw.println(status);
}
}
i am presenting my code...where i hv used HTTP Basic Auth to provide the users credentials to stripe.com
Try: new UsernamePasswordCredentials("<api-key>", "")
Hope this will help you.
Here API_KEY means secrete key
HttpResponse httpResponse;
String request ='card[number]='+card_name+'&card[exp_year]='+card_exp_year+'&card[exp_month]='+card_exp_month+'&card[cvc]='+card_cvv+'&amount='+amount+ '¤cy='+currency;
Http httpObject = new Http();
HttpRequest httpRequest = new HttpRequest();
httpRequest.setEndpoint(sHttpEndPoint);
httpRequest.setMethod('POST');
Blob headerValue = Blob.valueOf(API_KEY + ':');
String authorizationHeader = 'BASIC ' +
EncodingUtil.base64Encode(headerValue);
httpRequest.setHeader('Authorization', authorizationHeader);
httpRequest.setBody(request);
httpResponse = httpObject.send(httpRequest);
Related
I'm trying to get an OAuth token using a ClientID and SecretID.
My code so far:
Dim clientId As String = "8cd6b80dd822961f362"
Dim clientSecret As String = "5afbd4bb280f29cba5ec1f362"
Dim credentials = String.Format("{0}:{1}", clientId, clientSecret)
Dim headerValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials))
Dim content = New FormUrlEncodedContent(New Dictionary(Of String, String) From {
{"client_id", clientId},
{"client_secret", clientSecret},
{"response_type", "code"},
{"redirect_uri", "https://somesite.com/"},
{"grant_type", "authorization_code"}})
Dim requestMessage = New HttpRequestMessage(HttpMethod.Post, "https://api.site.com/oauth2/authorize")
requestMessage.Headers.Authorization = New AuthenticationHeaderValue("Basic", headerValue)
requestMessage.Content = content
Dim client As HttpClient = New HttpClient()
Dim task = client.SendAsync(requestMessage)
Dim response = task.Result
response.EnsureSuccessStatusCode()
Dim responseBody As String = response.Content.ReadAsStringAsync().Result
MsgBox(responseBody)
The above code returns the HTML for the redirect_uri site and not a token.
What am I missing or doing wrong?
Using Postman and the credentials provided I managed to get the token.
The second step of a code flow uses the token endpoint, not the authorize endpoint. Your payload looks correct though. Try posting it to this endpoint:
https://api.site.com/oauth2/token
By default HttpClient is using AllowAutoRedirect = true. The documentation says:
The Authorization header is cleared on auto-redirects and the handler automatically tries to re-authenticate to the redirected location. No other headers are cleared. In practice, this means that an application can't put custom authentication information into the Authorization header if it is possible to encounter redirection.
So depending on the setup of the server you might have to create a CookieContainer and do the redirecting on your own.
Update:
The usage of a certificate store is something I didn't get from your question. If you want to do similar handling of certificates like browsers do you have to implement this feature yourself. Here is a C# example of how you can extend WebClient class with a dedicated CookieContainer and X509 certificate handling. I used it with smart card reader. It should work similar in vb.net. Hope it helps to find the right .Net classes and how to put things together:
public class SmartCardClient : WebClient
{
public CookieContainer Cookies = new CookieContainer();
public Uri LastResponseUri = null;
public X509Certificate2 cert = null;
private string IssuerName = null;
public SmartCardClient(string issuerName)
{
IssuerName = issuerName;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
SelectCertificate();
}
protected override WebRequest GetWebRequest(Uri uri)
{
var request = base.GetWebRequest(uri) as HttpWebRequest;
LastResponseUri = null;
if (request != null)
{
request.CookieContainer = Cookies;
request.UseDefaultCredentials = true;
request.AllowAutoRedirect = true;
}
return request;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
LastResponseUri = response.ResponseUri;
return response;
}
public void SelectCertificate()
{
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection certs = (X509Certificate2Collection)store.Certificates
.Find(X509FindType.FindByTimeValid, DateTime.Now, false)
.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false)
.Find(X509FindType.FindByIssuerName, IssuerName, false);
if (certs.Count > 1)
certs = X509Certificate2UI.SelectFromCollection(
certs, "Select Certificate", "Please select a certificate:",
X509SelectionFlag.MultiSelection
);
if (certs.Count > 0)
cert = certs[0];
store.Close();
}
}
I am trying to send Get request using RestSharp but getting this message in response:Bad Request/
{"Message":"P1001: No Ids were specified"}. Could someone help please to figure out that? Seems like it's not adding Parameter list to the Request Body...
Here is my code:
public partial class DTO
{
public List<string> evidenceIds { get; set; }
}
public RestRequest GetPlayRequest(Method requestType, string token)
{
DTO MyObject = new DTO();
MyObject.evidenceIds = new List<string>();
MyObject.evidenceIds.Add("6F00CAE1-F16E-47F6-AF3F-D10305DD7859");
string jsonString = JsonConvert.SerializeObject(MyObject);
var restRequest = new RestRequest(requestType);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddParameter("text/json", jsonString, ParameterType.RequestBody);
restRequest.AddHeader("Organization", "Bofa");
restRequest.AddHeader("Username", "Admin");
restRequest.AddParameter("Authorization", "Bearer " + token, ParameterType.HttpHeader);
return restRequest;
}
The request with all params
The Content response after sending the request
I can suggest the following:
public RestRequest GetPlayRequest(Method method, string token)
{
var obj = new DTO { evidenceIds = new string[]
{"6F00CAE1-F16E-47F6-AF3F-D10305DD7859" }
};
return new RestRequest(method)
.AddJsonBody(obj)
.AddHeader("Organization", "Bofa")
.AddHeader("Username", "Admin");
.AddHeader("Authorization", $"Bearer {token}");
}
My question is that do i have to make a separate request to check SSL Pinning before every Get/Post Request
OkHttpClient client = new OkHttpClient.Builder().certificatePinner(
new CertificatePinner.Builder()
.add(pinningUrl, "sha256/invalidPIN")
.build()).build();
Request request = new Request.Builder()
.url(pinningUrl)
.build();
Response response = client.newCall(request).execute();
Or can i check it with every Get/Post like this
CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add(pinningUrl, "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") .build();
OkHttpClient client = new OkHttpClient().newBuilder().certificatePinner(certificatePinner).build();
Request request = new Request.Builder() .url(getResources().getString(R.string.server_url_user_mgmt_services))
.addHeader("Content-Type", "application).post(body)
.build();
client.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
pd.dismiss();
Toast.makeText(LoginActivity.this, "Some error occured!\nTry Again", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().toString();
}
});
If i check it on every request the request is executed but it does not check for certificate help me with this.
Based on your first code example it looks like you are trying to pin with a URL instead of a hostname or wildcard.
You should configure it once on your OkHttpClient per host and then just make your normal requests. The pins you define should have the host as the key, not the url.
https://square.github.io/okhttp/3.x/okhttp/okhttp3/CertificatePinner.html
String hostname = "publicobject.com";
CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add(hostname, "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
.build();
OkHttpClient client = OkHttpClient.Builder()
.certificatePinner(certificatePinner)
.build();
Request request = new Request.Builder()
.url("https://" + hostname)
.build();
client.newCall(request).execute();
private void setUpRestClient() {
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Accept", "application/pyur.v1")
.header("Authorization", new SharedPreferencesUtil(getBaseContext()).getToken())
.header("Content-Type", "application/json")
.method(original.method(),original.body())
.build();
return chain.proceed(request);
}
});
RestClient.getInstance().configureRestAdapter(this, getResources().getString(R.string.base_url),client);
}
public void configureRestAdapter(final Context context, String baseUrl, OkHttpClient client) {
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
service = retrofit.create(NetworkServiceInterface.class);
}
This now gives me a failure return in Retrofit 2.0, originally I had it without the "Authorization" header and it was giving me unauthorized, which is understandable. But now I'm authorizing it with my auth token and it fails. New to Retrofit 2.0, thanks --
You can pass Authorization Header as:
#GET("/v1/OrderReport.json")
Call<POJO_Class> getExampleMethod(#Header("Authorization") String token, #Query("id") String id);
and then call as:
getExampleMethod("Basic " + token, id);
You can add Authorization Header for every calls using Interceptor in Retrofit 2, by using the OkHttpClient.Builder class. Like this.
import okhttp3.OkHttpClient;
import okhttp3.Interceptor;
OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
//getAccessToken is your own accessToken(retrieve it by saving in shared preference or any other option )
if(getAccessToken().isEmpty()){
PrintLog.error("retrofit 2","Authorization header is already present or token is empty....");
return chain.proceed(chain.request());
}
Request authorisedRequest = chain.request().newBuilder()
.addHeader("Authorization", getAccessToken()).build();
PrintLog.error("retrofit 2","Authorization header is added to the url....");
return chain.proceed(authorisedRequest);
}}).build();
And add this client object to the retrofit object.
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) //BaseURL always ends with "/"
.addConverterFactory(GsonConverterFactory.create())
.client(defaultHttpClient)
.build();
Now for every calls that you make using the retrofit object will add the "Authorization" header along with the url. And also we handle the condition that if the authorization value is empty, then we simply omit the Authorization header part for the request call.
From Retrofit:2.0
you have to use OkHttpClient.Builder() class to add Interceptors.
So you have to change your code like this.
OkHttpClient client = new OkHttpClient.Builder();
client.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Accept", "application/pyur.v1")
.header("Authorization", new SharedPreferencesUtil(getBaseContext()).getToken())
.header("Content-Type", "application/json")
.method(original.method(),original.body())
.build();
return chain.proceed(request);
}
}).build();
Running a java main program to call twitter streaming api. I have generated a bearer token and passing to the api. But getting the error response Error 401 Unauthorized
Is passing the bearer token right way to authenticate? If not what is the right way to do this?
SSLConnectionSocketFactory sslsf = getSSLConnectionFactory();
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpHost target = new HttpHost("stream.twitter.com", 443, "https");
new BasicHttpContext();
HttpPost httpPost = new HttpPost("/1.1/statuses/filter.json");
StringEntity postEntity = new StringEntity("track=birthday","UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);
//httpPost.setHeader("Authorization", "Bearer " + Base64.encodeBase64(bearerToken.getBytes()));
httpPost.setHeader("Authorization", "Bearer " + bearerToken);
httpPost.setHeader("User-Agent", "Your Program Name");
httpPost.setHeader("Host", "stream.twitter.com");
HttpResponse response = httpClient.execute(target, httpPost,new BasicHttpContext());
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = null;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
if(buffer.length()>30000) break;
}
System.out.println(buffer);
//return new EventImpl(buffer.toString().getBytes());
} catch (Exception e) {
e.printStackTrace();
}