I'm using DotNetOpenAuth to aunthenticate a user, and I'm unable to make it work. This is my code:
public string AuthenticateUser(
string key, string secret, string user, string password,
AuthorizationServerDescription serviceDescription)
{
UserAgentClient agent = new UserAgentClient(
serviceDescription,
key,
secret);
IAuthorizationState authState = mConsumer.ExchangeUserCredentialForToken(
user,
password,
GetScope());
if (authState != null)
{
return authState.Token;
}
}
I'm trying to authenticate against Google and WindowsLive, without sucess in both cases.
Google
These are the configuration parameters used to access the Google OAuth service:
AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth")
TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token")
ProtocolVersion = ProtocolVersion.V20
State = "/profile"
Scope = "https://www.googleapis.com/auth/userinfo.email"
Error obtained:
---------------------------
Error
---------------------------
Error occurred while sending a direct message or getting the response.
---------------------------
OK
---------------------------
Windows Live
These are the parameters used to acces the Windows Live Outh service:
TokenEndpoint = new Uri("https://oauth.live.com/token"),
AuthorizationEndpoint = new Uri("https://oauth.live.com/authorize")
ProtocolVersion = ProtocolVersion.V20
State = null
Scope = "wl.signin"
Error obtained:
---------------------------
Error
---------------------------
Unexpected response Content-Type text/html
---------------------------
OK
---------------------------
I also tested using the ClientCredentialApplicator in all ways:
NetworkCredential
NoSecret
PostParameter
Am I doing something wrong? Someone could show me a working example of ExchangeUserCredentisForToken?
Thanks in avance.
The resource owner credential grant only works when allowed by the authorization server. I believe both Google and Microsoft deliberately do not support this, since they don't want 3rd party apps taking user credentials directly.
Related
I have just setup a new project and added the following scopes for "Web application".
email, and send mail
I have also enabled GMailAPI from library
After this I have created credentials. Then edit > redirect_uri
I am not sure what this uri should be but I have tried almost everything here
Gmail error message state "If you are a developer of this app see error details"
the url mentioned here : http:\x.x.x.x:1234\authorize\
with and without ending slash
P.S: when I type above uri in my browser, I get to a break point in my application
my home page url
http:\localhost\default.aspx
my calling page uri
http:\localhost\member\create.aspx
None of these work and I still get redirect_uri_mismatch Access Blocked error
My code is still running on my local machine and not available in google cloud.
vb.net code
Dim credential As UserCredential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets With {
.ClientId = "xxx",
.ClientSecret = "xxx"
},
{"https://www.googleapis.com/auth/gmail.send"},
"user",
CancellationToken.None)
Update
I got to know that AuthorizeAsync is for installed applications and not for web apps, here is my updated code...which is not sending me back a token.
Public Function DoOauthAndSendEmail(subject As String, body As String, recipients As String) As Task
Dim fromEmail As String = ConfigurationSettings.AppSettings("ContactEmail")
Dim MailMessage As MailMessage = New MailMessage(fromEmail, recipients, subject, body)
'Specify whether the body Is HTML
MailMessage.IsBodyHtml = True
'Convert to MimeMessage
Dim Message As MimeMessage = MimeMessage.CreateFromMailMessage(MailMessage)
Dim rawMessage As String = Message.ToString()
Dim flow As IAuthorizationCodeFlow = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer With {
.ClientSecrets = New ClientSecrets With {
.ClientId = "CLIENT_ID",
.ClientSecret = "CLIENT_SECRET"
},
.Scopes = {GmailService.Scope.GmailSend}
})
Dim token As Responses.TokenResponse = New Responses.TokenResponse()
If flow IsNot Nothing And token IsNot Nothing Then
Dim credential As UserCredential = New UserCredential(flow, "user", token)
Dim success As Boolean = credential.RefreshTokenAsync(CancellationToken.None).Result
Dim gmail As GmailService = New GmailService(New Google.Apis.Services.BaseClientService.Initializer() With {
.ApplicationName = "APP_NAME",
.HttpClientInitializer = credential
})
gmail.Users.Messages.Send(New Message With {
.Raw = Base64UrlEncode(rawMessage)
}, "me").Execute()
End If
End Function
You are looking in the wrong place for the redirect uri's it is found under credentials then edit your web app client
Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications
update Installed app
The code you are using GoogleWebAuthorizationBroker.AuthorizeAsync is used for authorizing an installed application. In this instance you need to make sure that you have created an installed application credentials on google cloud console.
How to create installed application credetilas.
You should not be seeing a redirect uri error if you have created the correct credentials type for you to match the code you are using.
I successfully authenticate using OAuth2 to Salesforce and i get back
access_token,signature,scope,id_token,instance_url,id,token_type,issued_at in json format.
Now in my c# code I make calls using Soap , the first is login, but this is no longer needed as I have authenticated already with OAuth.
I try to setup the service and then call
_service = new SalesForceEnterpriseService.SforceService() { Timeout = 60000, Url =
instance_url };
_service.SessionHeaderValue = new SessionHeader() { sessionId = access_token };
_service.QueryOptionsValue = new QueryOptions { batchSize = 200, batchSizeSpecified =
true };
DescribeGlobalResult result = _service.describeGlobal(); <----but it fails here
I get an exception:
Client found response content type of 'text/html; charset=UTF-8', but expected
'text/xml'.
The request failed with the error message:
What i found is that the Url returned with a Login from Soap is different to that returned after authenticating using OAuth2.
OAuth returns somethin like
"https://<mysalesforce>.salesforce.com
whereas the Soap Login returns
"https://<mysalesforce>.salesforce.com/services/Soap/u/54.0/<??number>
Any help with this would be great.
I have a Angular 4 site that I’m trying to use Microsoft Graph implicit flow to authenticate users then use token to call our APIs at another endpoint, so I use msal.js to get the access token.
After I bring the access token to my API endpoint and try to valid it, the token cannot be valid. I got a SignatureVerificationFailedException.
My understanding is that the access token is for Microsoft Graph API, not for my APIs, so I cannot valid it. (I can use it to call Graph API without problem)
How can I get a access token(not id token) using msal.js that can be used for my APIs but not Microsoft Graph? Thanks!
The reason I'm sending access token instead of id token to the API endpoint is that I want to get the puid claim from the token, which is not available for id token.
Here is what I was trying to valid the access token I got from client which is using msal.js
const string authority = "https://login.microsoftonline.com/common";
const string audience = "https://graph.microsoft.com";
string issuer = null;
string stsDiscoveryEndpoint = $"{authority}/v2.0/.well-known/openid-configuration";
List<SecurityToken> signingTokens = null;
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);
var config = await configManager.GetConfigurationAsync();
issuer = config.Issuer;
signingTokens = config.SigningTokens.ToList();
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidAudience = audience,
ValidIssuer = issuer,
ValidateIssuer = false,
IssuerSigningTokens = signingTokens,
CertificateValidator = X509CertificateValidator.None
};
try
{
// Validate token.
SecurityToken validatedToken = new JwtSecurityToken();
var claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out validatedToken);
var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity;
return ExtractAuthenticatedUserFromClaimsIdentity(claimsIdentity);
}
catch (SignatureVerificationFailedException)
{
throw;
}
Thanks,
If you want to get an access token for your API rather than the Microsoft Graph API, you must specify your API as the resource in the token request.
Make sure that:
Your Web API has configured OAuth2Permission Scopes. See here. Configuring a resource application to expose web APIs
Your Client Application has selected permissions to those exposed APIs. Configuring a client application to access web APIs
Finally, make sure you use your Web API's App ID URI or App ID GUID as the resource value in your token request.
Let me know if this helps!
My windows service is collect instagram datas from instagram api. I was using client_id but this uses format is removed.
Instagram api is want to access_token but Oauth 2.0 is web-based. or not?
I using .NET and my application type is windows service and web request don't work because this call url: "https://www.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code" is have one more contain redirect. so web response haven't contain my web application link also auto redirect is open..
what should I do?
Thanks..
Steps to get instagram access token
register ur application in instagram account.
get a client id and client secret.
Step 1: HIT the below url.
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
step 2: after hitting above url you will be taken to login page. enter the login credentials and take the code from address bar.
it will be live for only 20 seconds i guess.
step 3: The code which you got put it in CODE parameter in the below source code, then run the below code in console application n hit breakpoint at response. you will get access token and userid.
public void GetDataInstagramToken()
{
try
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "CLIENT-ID");
parameters.Add("client_secret", "CLIENT-Secret");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "REDIRECT-URI");
parameters.Add("code", "CODE");
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
var response = System.Text.Encoding.Default.GetString(result);
// deserializing nested JSON string to object
var jsResult = (JObject)JsonConvert.DeserializeObject(response);
string accessToken = (string)jsResult["access_token"];
}
catch (Exception)
{
//exception catch
}
}
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.