I am trying to get access token for which I need OAuth verifier. I am using TokenSecretVerifierHolder class to get token, token secret and verifier but I am only getting the value of token, token secret, however the verifier value is coming aa null. Here is my code.
public TokenSecretVerifierHolder getRequestToken() {
try {
OAuthAccessor accessor = getAccessor();
OAuthClient oAuthClient = new OAuthClient(new HttpClient4());
List<OAuth.Parameter> callBack;
if ((this.callback == null) || ("".equals(this.callback))) {
callBack = Collections.emptyList();
} else {
callBack = ImmutableList.of(new OAuth.Parameter("oauth_callback", this.callback));
}
OAuthMessage message = oAuthClient.getRequestTokenResponse(accessor, "POST", callBack);
TokenSecretVerifierHolder tokenSecretVerifier = new TokenSecretVerifierHolder();
tokenSecretVerifier.token = accessor.requestToken;
tokenSecretVerifier.secret = accessor.tokenSecret;
tokenSecretVerifier.verifier = message.getParameter("oauth_verifier");
return tokenSecretVerifier;
} catch (Exception e) {
throw new RuntimeException("Failed to obtain request token", e);
}
}
private String getAccessToken() {
AtlassianOAuthClientRequest jiraoAuthClient = getJiraOAuthClient();
TokenSecretVerifierHolder requestToken = jiraoAuthClient.getRequestToken();
String authorizeUrl = jiraoAuthClient.getAuthorizeUrlForToken(requestToken.token);
String token = requestToken.token;
String tokenSecret = requestToken.secret;
String verifier = requestToken.verifier;
String accessToken = jiraoAuthClient.swapRequestTokenForAccessToken(token, tokenSecret, verifier);
String verifier = requestToken.verifier;
System.out.println("Access token is : " + accessToken);
return accessToken;
}
After retreiving the value of token, token secret and verifier I am passing it to get the access token value. What I want is that after I acknowledge the authorizeUrl it should return me the value of Oauth verifier. In my case its returning as null.
The required value of verifier is returned to you during HTTP redirect to your callback URL - the redirect happens with URL like https://consumer.url/?oauth_token=TOKEN&oauth_verifier=VERIFIER, so value of oauth_verifier parameter is what you need.
Related
Why context.SerializeTicket() and access_token not the same?
public override async Task CreateAsync(AuthenticationTokenCreateContext context)
{
//if (string.IsNullOrEmpty(context.Ticket.Identity.Name)) return;
var clientId = context.OwinContext.Get<string>("as:client_id");
var refreshTokenId = Guid.NewGuid().ToString("n");
var refreshToken = new RefreshToken
{
Id = refreshTokenId,
ClientId = clientId,
UserName = context.Ticket.Identity.Name,
IssuedUtc = DateTime.Now,
ExpiresUtc = DateTime.Now.AddDays(30)
};
context.Ticket.Properties.IssuedUtc = refreshToken.IssuedUtc;
context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiresUtc;
refreshToken.ProtectedTicket = context.SerializeTicket();
await _cacheManager.SetAsync(refreshTokenId, refreshToken, TimeSpan.FromDays(10));
context.SetToken(refreshTokenId);
}
Result:
refreshToken.ProtectedTicket = "M2NQCH_kdzOJyHj9Sc-i_WjZtwS1Tqe3WjFXf-Laja80RUw_cOIZ9IH-Bhh3rlZx64lYxj6IUILJsBNG5FPMm7edaJqYA-qEsqYJjLTSUgSEIikeiomxcQA4qK2397HwhhzwA10QNMLFAUVscEE8MzJ4kGn_qanMP-xW3YVMycQLgGBjC5pDqBd8Q1U0nHQ5Cwe1OvWrngnq06Qe5QvZfRrMppw8MyyoliqRtPyq0UU";
Postman:
{"access_token":"jL1f5jI16pZpAmeNIvOCXe7zMEi1WT3ElOt1Tau-vfDV3iBNm6cH6oXz4XzLW2Y-2Me2Hyvl09R3vHWedlYUTiGAmFK4m75jomeqNbK2L9nnOv8-1N6iaEpB2ppT9bYLF9c77SMtmcQoLG0iBpdNu9fVObl5u5W7M5yxi6Kjq5MYdYLdzczfkaP3QA1csHdWeiuCEHf9Dw6F8XKYRpqFqUiSzFcqUW3qXcWrTF1Hfsk","token_type":"bearer","expires_in":2591999,"refresh_token":"05d7b5373b8c490fb136afe985d756ab"}
access_token is the token issued when the user is authenticated.
context.SerializeTicket() serializes the refresh token.
Why context. SerializeTicket ( ) and access_token not the same?
They are different because they represent different things.
[bonus]
refresh_token contains the key used to retrieve and deserialize the refresh token. This is done inside the Receive or ReceiveAsync method.
I am using OAuth authenication in Jira to test some methods in jira using JIRA Rest Java Client. I have got the access token using OAuth authenication that I need to pass on Jira URL. Here is all what I have got to get access token.
Token is 38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Token secret is cnDSL8oJyuoaQdRcFDwgHzLppSshQn9b
Retrieved request token. go to http://bmh1060149:8080/plugins/servlet/oauth/authorize?oauth_token=38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Access token is : 015CeJiH8cpI5R3OKpNco158kApq8YwV
Now I am passing that access token to Jira URL but I am getting an empty array. Please let me know where I am doing wrong or what changes do I need to incorporate into my code to make this thing work. Here is my code.
public void getAllIssueTypesUsingOAuth(JiraCQCredential jcqcred) {
System.out.println("Inside getAllIssuetypeAssociatedToProject for JiraAdapterImpl");
//String username = jcqcred.getUserName();
//String password = jcqcred.getPassword();
String jiraURL = jcqcred.getJiraUrl();
if (!jiraURL.endsWith("/")) {
jiraURL = jiraURL + "/";
}
try {
String accessToken = JiraAdapterImpl.getAccessToken(); // This method is giving me access token
URL url = new URL(jiraURL + "rest/api/2" + "/" + "issuetype?access_token=" + accessToken);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String issueTypes = sb.toString();
System.out.println("Issuetype associated to project are\n" + issueTypes);
JSONArray jsonArray = new JSONArray(issueTypes);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String issueNames = (String) jsonObject.get("name");
System.out.println(issueNames);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Its giving me an empty array like []
Hi After searching the little bit I finally managed to a find the solution to the above problem. After getting the access token just pass that access token to the makeAuthenticatedRequest(url, accessToken) method that will give you the resultant data which you want to retrive. Here url is the url which you want to hit to get the resultant data.
private AtlassianOAuthClient getJiraOAuthClient() {
final String baseURI = "http://bmh1060149:8080";
final String consumerKey = "hardcoded-consumer";
final String consumerPrivatekey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFkPMZQaTqsSXI+bSI65rSVaDzic6WFA3WCZMVMi7lYXJAUdkXo4DgdfvEBO21Bno3bXIoxqS411G8S53I39yhSp7z2vcB76uQQifi0LEaklZfbTnFUXcKCyfwgKPp0tQVA+JZei6hnscbSw8qEItdc69ReZ6SK+3LHhvFUUP1nLhJDsgdPHRXSllgZzqvWAXQupGYZVANpBJuK+KAfiaVXCgA71N9xx/5XTSFi5K+e1T4HVnKAzDasAUt7Mmad+1PE+56Gpa73FLk1Ww+xaAEvss6LehjyWHM5iNswoNYzrNS2k6ZYkDnZxUlbrPDELETbz/n3YgBHGUlyrXi2PBjAgMBAAECggEAAtMctqq6meRofuQbEa4Uq5cv0uuQeZLV086VPMNX6k2nXYYODYl36T2mmNndMC5khvBYpn6Ykk/5yjBmlB2nQOMZPLFPwMZVdJ2Nhm+naJLZC0o7fje49PrN2mFsdoZeI+LHVLIrgoILpLdBAz/zTiW+RvLvMnXQU4wdp4eO6i8J/Jwh0AY8rWsAGkk1mdZDwklPZZiwR3z+DDsDwPxFs8z6cE5rWJd2c/fhAQrHwOXyrQPsGyLHTOqS3BkjtEZrKRUlfdgV76VlThwrE5pAWuO0GPyfK/XCklwcNS1a5XxCOq3uUogWRhCsqUX6pYfAVS6xzX56MGDndQVlp7U5uQKBgQDyTDwhsNTWlmr++FyYrc6liSF9NEMBNDubrfLJH1kaOp590bE8fu3BG0UlkVcueUr05e33Kx1DMSFW72lR4dht1jruWsbFp6LlT3SUtyW2kcSet3fC8gySs2r6NncsZ2XFPoxTkalKpQ1atGoBe3XIKeT8RDZtgoLztQy7/7yANQKBgQDQvSHEKS5SttoFFf4YkUh2QmNX5m7XaDlTLB/3xjnlz8NWOweK1aVysb4t2Tct/SR4ZZ/qZDBlaaj4X9h9nlxxIMoXEyX6Ilc4tyCWBXxn6HFMSa/Rrq662Vzz228cPvW2XGOQWdj7IqwKO9cXgJkI5W84YtMtYrTPLDSjhfpxNwKBgGVCoPq/iSOpN0wZhbE1KiCaP8mwlrQhHSxBtS6CkF1a1DPm97g9n6VNfUdnB1Vf0YipsxrSBOe416MaaRyUUzwMBRLqExo1pelJnIIuTG+RWeeu6zkoqUKCAxpQuttu1uRo8IJYZLTSZ9NZhNfbveyKPa2D4G9B1PJ+3rSO+ztlAoGAZNRHQEMILkpHLBfAgsuC7iUJacdUmVauAiAZXQ1yoDDo0Xl4HjcvUSTMkccQIXXbLREh2w4EVqhgR4G8yIk7bCYDmHvWZ2o5KZtD8VO7EVI1kD0z4Zx4qKcggGbp2AINnMYqDetopX7NDbB0KNUklyiEvf72tUCtyDk5QBgSrqcCgYEAnlg3ByRd/qTFz/darZi9ehT68Cq0CS7/B9YvfnF7YKTAv6J2Hd/i9jGKcc27x6IMi0vf7zrqCyTMq56omiLdu941oWfsOnwffWRBInvrUWTj6yGHOYUtg2z4xESUoFYDeWwe/vX6TugL3oXSX3Sy3KWGlJhn/OmsN2fgajHRip0=";
AtlassianOAuthClient jiraoAuthClient = new AtlassianOAuthClient(consumerKey, consumerPrivatekey, baseURI, "");
return jiraoAuthClient;
}
Here is the code to get Access Token
private String getAccessToken() {
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
TokenSecretVerifierHolder requestToken = jiraoAuthClient.getRequestToken();
String authorizeUrl = jiraoAuthClient.getAuthorizeUrlForToken(requestToken.token);
String token = requestToken.token;
String tokenSecret = requestToken.secret;
System.out.println("Token is " + requestToken.token);
System.out.println("Token secret is " + requestToken.secret);
System.out.println("Retrieved request token. go to " + authorizeUrl);
String accessToken = jiraoAuthClient.swapRequestTokenForAccessToken(token, tokenSecret, "");
System.out.println("Access token is : " + accessToken);
return accessToken;
}
This is the method you call to retrieve the data.
public void getAllCommentOfIssueUsingOAuth() {
logger.info("Inside getAllCommentOfIssue for JiraAdapterImpl");
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
String accessToken = getAccessToken();
String url = "your Jira URL";
String responseAsString = jiraoAuthClient.makeAuthenticatedRequest(url, accessToken);
System.out.println(responseAsString);
}
This will give you the resultant JSON data or XML data in resultantString.
Is there any way to get SAML token for the Application Pool Identity User (configured user)?
when we configure application pool dentity stores config entries (user name & password) in applicationHost.config under %systemroot%\System32\Inetsrv\config path.
When application starts, it picks the user name and encrypted password for authentication. After successful authentication, will it follow token based authentication for subsequent calls or will always follows basic authentication ?
If it token based then how can i get the SAML token for application pool identity user, after the first response?
if any links please let me know.
Thanks in advance.
To Get SAML Assertion for Application pool Identity Or Logged on user :
string rpLoginUrl = string.Format(SapConfiguration.AdfsSignInUrl, SapConfiguration.AdfsInstance, HttpUtility.UrlEncode(GetSapTokenServiceUrl));
string htmlContent;
try
{
do
{
var result = await Client.GetAsync(rpLoginUrl);
htmlContent = await result.Content.ReadAsStringAsync();
IEnumerable<string> values;
if (result.Headers.TryGetValues("location", out values))
{
foreach (string s in values)
{
if (s.StartsWith("/"))
{
rpLoginUrl = rpLoginUrl.Substring(0, rpLoginUrl.IndexOf("/adfs/ls", StringComparison.Ordinal)) + s;
}
else
{
rpLoginUrl = s;
}
}
}
else
{
rpLoginUrl = "";
}
} while (!string.IsNullOrEmpty(rpLoginUrl));
}
catch (Exception exp)
{
var additionalInfo = $" additionalInfo : [rpLoginUrl: {rpLoginUrl}]";
throw new SecurityException($"SapAuthorization.GetSamlResponseForProcessIdentityAsync is failed, {additionalInfo}", exp);
}
var reg = new Regex("SAMLResponse\\W+value\\=\\\"([^\\\"]+)\\\"");
var matches = reg.Matches(htmlContent);
string lastMatch = null;
foreach (Match m in matches)
{
lastMatch = m.Groups[1].Value;
}
return lastMatch;
Ans 1: By Using Adal flow to get Jwt token for Logged on User,
if (!AdfsConfiguration.IsInitialized) throw new SecurityException(Constants.AdfsConfigurationInitilizationExceptionMessage);
if (string.IsNullOrEmpty(AdfsConfiguration.AdfsAuthorityUrl)) throw new SecurityException(Constants.AdfsConfigurationAdfsAuthorityUrlInitilizationExceptionMessage);
try
{
var authenticationContext = new AuthenticationContext(string.Format(AdfsConfiguration.AdfsAuthorityUrl, AdfsConfiguration.AdfsInstance, AdfsConfiguration.Resource), false);
var asyncRequest = authenticationContext.AcquireTokenAsync(AdfsConfiguration.Resource, AdfsConfiguration.ClientId, new Uri(AdfsConfiguration.RedirectUri), new PlatformParameters(PromptBehavior.Auto));
var accessToken = asyncRequest.Result.AccessToken;
return accessToken;
}
catch (Exception exp)
{
var additionalInfo = $" additionalInfo : [authenticationContext : {string.Format(AdfsConfiguration.AdfsAuthorityUrl, AdfsConfiguration.AdfsInstance, AdfsConfiguration.Resource)}]";
throw new SecurityException($"AdfsAuthorization.GetAdfsOAuthJwtAccessTokenForWinAppUserUsingAdal is failed, {additionalInfo}", exp);
}
Ans 2: By Auth code flow to get Jwt token for logged on user or Application pool identity user.
step 1 : Get Auth code from Adfs server
var authUrl = string.Format(AdfsConfiguration.AdfsAuthUrl, AdfsConfiguration.AdfsInstance, AdfsConfiguration.ClientId, AdfsConfiguration.Resource, AdfsConfiguration.UrlEncodedRedirectUri);
var authCode = "";
try
{
do
{
var result = await Client.GetAsync(authUrl);
await result.Content.ReadAsStringAsync();
IEnumerable<string> values;
if (result.Headers.TryGetValues("location", out values))
{
foreach (string s in values)
{
if (s.Contains("code="))
{
authUrl = "";
authCode = s.Substring(s.IndexOf("code=", StringComparison.Ordinal) + 5);
}
else
{
authUrl = s;
}
}
}
else
{
authUrl = "";
}
} while (!string.IsNullOrEmpty(authUrl));
return authCode;
}
catch (Exception exp)
{
var additionalInfo = $"additionalInfo : [authUrl: {authUrl}]";
throw new SecurityException($"AdfsAuthorization.GetAuthCodeForWinAppUserAsync is failed, {additionalInfo}", exp);
}
Step 2 : Pass Auth code to get jwt token from Adfs server
if (!AdfsConfiguration.IsInitialized) throw new SecurityException(Constants.AdfsConfigurationInitilizationExceptionMessage);
var client = new WebClient();
try
{
if (AdfsConfiguration.UseProxy == "Y")
{
var proxyObject = new WebProxy("Proxy", 80) { Credentials = CredentialCache.DefaultNetworkCredentials };
client.Proxy = proxyObject;
}
//Uri address = new Uri(String.Format("https://{0}/adfs/oauth2/token/", AdfsInstance));
Uri address = new Uri(string.Format(AdfsConfiguration.AdfsTokenServiceUrl, AdfsConfiguration.AdfsInstance));
Uri redirectAddress = new Uri(AdfsConfiguration.RedirectUri);
NameValueCollection values = new NameValueCollection
{
{"client_id", AdfsConfiguration.ClientId},
{"grant_type", "authorization_code"},
{"code", code},
{"redirect_uri", redirectAddress.ToString()}
};
byte[] responseBytes = client.UploadValues(address, "POST", values);
string response = System.Text.Encoding.UTF8.GetString(responseBytes);
return response;
}
catch (Exception exp)
{
var additionalInfo = $" additionalInfo : [address: {string.Format(AdfsConfiguration.AdfsTokenServiceUrl, AdfsConfiguration.AdfsInstance) }, redirect Uri :{AdfsConfiguration.RedirectUri}]";
throw new SecurityException($"AdfsAuthorization.GetAdfsOAuthTokenByAuthCode is failed, {additionalInfo}", exp);
}
finally
{
client.Dispose();
}
I want to oauth authentication like
Login using Google OAuth 2.0 with C#
But i don't want to authentication prompt popup
i want to get token directly without popup..
public ActionResult CodeLele()
{
if (Session.Contents.Count > 0)
{
if (Session["loginWith"] != null)
{
if (Session["loginWith"].ToString() == "google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
// This is where you want to add the code if login is successful.
// getgoogleplususerdataSer(accessToken);
}
else
{ }
}
else
{ }
}
else
{ }
}
}
catch (WebException ex)
{
try
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
//var messageFromServer = obj.error.message;
//return messageFromServer;
return obj.error_description;
}
catch (Exception exc)
{
throw exc;
}
}
}
}
}
return Content("done");
}
public ActionResult JeClick()
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["loginWith"] = "google";
return Redirect(Googleurl);
}
The credentials window (popup) is how you ask the user if you can access their data. There is no way to get access to a users data without asking the user first if you may access their data. That is how Oauth2 works.
If you are accessing your own data then you can use something called a Service account. Service accounts are pre authorized. You can take the service account and grant it access to your google calendar, you could give it access to a folder in Google drive. Then you can authenticate using the service account. Service accounts are like dummy users.
My article about service accounts: Google Developer service account
I am trying to get New access token for Oauth 2.0 with client credential. I am always getting Forbidden or unauthorized error. While I can directly login to url https://api.flipkart.net/oauth-service/oauth/token?grant_type=client_credentials&scope=Seller_Api and generate the token but going with below code I am not able to generate token
public static String getAccessToken(OAuth2Details oauthDetails) {
URL url;
HttpURLConnection con;
String accessToken = null;
try {
url = new URL("https://api.flipkart.net/oauth-service/oauth/token\?grant_type\=client_credentials\&scope=Seller_Api");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
con.setDoInput(true);
String clientId = oauthDetails.getClientId();
String clientSecret = oauthDetails.getClientSecret();
String scope = oauthDetails.getScope();
System.out
.println("Authorization server expects Basic authentication");
con.setRequestProperty(
OAuthConstants.AUTHORIZATION,
getBasicAuthorizationHeader(oauthDetails.getClientId(),
oauthDetails.getClientSecret()));
System.out.println("Retry with client credentials");
int code = con.getResponseCode();
System.out.print(con.getResponseMessage());
BufferedReader br = new BufferedReader(new InputStreamReader(
con.getErrorStream()));
if (code == 401 || code == 403) {
String s;
while ((s = br.readLine()) != null) {
System.out.print(br.readLine());
}
con.disconnect();
System.out
.println("Could not authenticate using client credentials.");
throw new RuntimeException(
"Could not retrieve access token for client: "
+ oauthDetails.getClientId());
}
}
Map<String, String> map = handleResponse(con);
accessToken = map.get(OAuthConstants.ACCESS_TOKEN);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return accessToken;
}
public static String getBasicAuthorizationHeader(String username,
String password) {
System.out.println("uu" + OAuthConstants.BASIC + " "
+ encodeCredentials(username, password));
return OAuthConstants.BASIC + " "
+ encodeCredentials(username, password);
}
public static String encodeCredentials(String username, String password) {
String cred = username + ":" + password;
return new String(Base64.encodeBase64(cred.getBytes()));
}
Remove the "\" from your url
url = new URL("https://api.flipkart.net/oauth-service/oauth/token?grant_type=client_credentials&scope=Seller_Api");
Also make the app-id and and secretlike this
<app-id>:<app_secret>
example kdfjkfjdsakfjd93842908039489:kdjsfkajidsjf8939034820
oauthDetails.getClientId()+":"+oauthDetails.getClientSecret()