The following is the request I'm using for the PATCH request for updating a user's password.
var token = TokenHelper.GetToken().AccessToken;
var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + person.UserPrincipalName);
client.Timeout = -1;
var request = new RestRequest(Method.PATCH);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + token);
request.AddParameter("application/json", "{\n\"passwordProfile\": {\n \"password\": \"" + person.NewPassword + "\"\n}\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
If I type a complex password I get:
{
"error": {
"code": "Request_BadRequest",
"message": "One or more properties contains invalid values.",
"innerError": {
"request-id": "5d97b465-7b27-4328-b0d9-4e9112f2257e",
"date": "2020-01-03T16:57:35"
}
}
}
If I type a simple password I get:
{
"error": {
"code": "Request_BadRequest",
"message": "The specified password does not comply with password complexity requirements. Please provide a different password.",
"innerError": {
"request-id": "986fd0da-90d4-45c7-ba74-1ba2bec61956",
"date": "2020-01-03T17:05:15"
}
}
}
If I type no password my response is a 204 No Content (success) and it is working fine if I update other fields(i.e. mobileNumber).
In order to change a user's password, you need to authenticate using either the Authorization Code or Implicit OAuth grant. In addition, you need to request the delegated scope Directory.AccessAsUser.All. From the documentation:
When updating the passwordProfile property, the following permission is required: Directory.AccessAsUser.All.
You should also set forceChangePasswordNextSignIn to true.
Related
I'm trying to Verify an Id Token in C#
I'm Creating the app like this:
AppOptions appOptions = new AppOptions()
{
Credential = GoogleCredential.FromFile(#"path/to/Credential.json"),
ServiceAccountId = "serviceAccId",
ProjectId = "ProjectId",
};
var MyApp = FirebaseApp.Create(appOptions);
The error message i get is: ID token has incorrect audience (aud) claim.
Any Ideas on what it could be? Thanks!
I added a few things to the code... the problem i get is in the last step, when i try to signIn with custom token.
It gives me an error stating that the reason was a MissingIdentifier.
using (var customToken = FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(authentication.FirebaseUser.LocalId))
{
string token = customToken.Result;
using (FirebaseAuthProvider auth = new FirebaseAuthProvider(new FirebaseConfig(FireBaseAppKey)))
{
using (test = auth.SignInWithCustomTokenAsync(token))
{
test.Wait();
}
}
customToken.Wait();
}
This is the message i get:
Exception occured while authenticating.
Url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key={0}
Request Data:
{
"token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJVaWQiOiIyM2E1ZGM0Ny03NDNhLTQzNDUtODc5Mi1lMDY5NjhkNDZjNGIiLCJpc3MiOiJmaXJlYmFzZS1hZG1pbnNkay0xb2ZxNEBhdXRodGVzdHByb2plY3QtYmVlMDkuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzdWIiOiJmaXJlYmFzZS1hZG1pbnNkay0xb2ZxNEBhdXRodGVzdHByb2plY3QtYmVlMDkuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJhdWQiOiJodHRwczovL2lkZW50aXR5dG9vbGtpdC5nb29nbGVhcGlzLmNvbS9nb29nbGUuaWRlbnRpdHkuaWRlbnRpdHl0b29sa2l0LnYxLklkZW50aXR5VG9vbGtpdCIsImV4cCI6MTU4NDU1NTAzNiwiaWF0IjoxNTg0NTUxNDM2fQ.nwvRalOpMs9LYIAFoFZ53Yu72kar9MNpO8gHBGZaMQcdx0ms7OIs0cYEsXUDYy0A_rNfOK03pIWc1y_w2rtIbl_Rg7oHY2u8YublHGe
-n6w9PjQpkONU3YEWHW9qnewhYPFqiLw94j8qEM9V3Bc0FCtspyv8i7Ra9-r2Gz9p88kvUHcIV8_qF9dN_4kNVNiVVHOIhFDQgDOnwUSobmp6aMVnsB9xRwv2_oiWc19s4HNXcNif12d7HHdeRauWVRoTYYvMjrgJTRUsGcB2YFZR8QhH7_0Fmn8bfbiJWP2maTXayL4sY2sIaEyJZDIaBDHkU8l_j_1KxBR7_FTv2Q5_DA\",
"returnSecureToken":true
}
Response: {
"error": {
"code": 400,
"message": "MISSING_IDENTIFIER",
"errors": [
{"message": "MISSING_IDENTIFIER\",
"domain": "global",
"reason": "invalid"
}
]
}
}
Reason: MissingIdentifier"}
This typically means that the ID token is for a different project than what you have the credentials file for. I recommend downloading a fresh credentials file from the Firebase/Cloud console for the project, and trying again.
I was able to make a oauth 2 login with Unity3d on Microsoft graph, I requested this permission for my app:
https://graph.microsoft.com/files.readwrite.appfolder
After the usual code flow (redirect to url, permission from user, auth code exchanged for token code and token for bearer auth code) I was able to log in.
Problem is that the upload of small files does not work:
https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content
I think this is the best I can do:
string myData = File.ReadAllText(Application.persistentDataPath + "/" + "provaupload.json");
using (UnityWebRequest www = UnityWebRequest.Post("https://graph.microsoft.com/v1.0/me/drive/root:/AppTry/provaupload.json:/createUploadSession", myData)) {
www.SetRequestHeader("Authorization", "Bearer <code>");
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError) {
Debug.Log(www.error + " " + www.downloadHandler.text);
} else {
Debug.Log("Upload complete! " + www.downloadHandler.text);
}
}
and I get this error:
Generic/unknown HTTP error {
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.",
"innerError": {
"request-id": "id",
"date": "2018-07-20T06:24:30"
}
}
I also tried the WWW class or Put instead of Post but I get "invalid API".
Maybe my problem is in the base url:
https://graph.microsoft.com/v1.0/me
or maybe it's in the path
root:/AppTry/provaupload.json
or maybe in the permission.
I don't really know.
If you know how to make a Rest call with Microsoft Graph and One drive (even not in unity3d and even if you don't know how to solve my specific problem) it would be great to get some example.
To upload file, use the UploadHandler. You must also encode the string as UTF8. As you mentioned in the comment section, it looks like you have to use PUT instead of POST and the url should be changed to something else.
Something more like this:
string myData = File.ReadAllText(Application.persistentDataPath + "/" + "provaupload.json");
string url = "https://graph.microsoft.com/v1.0/me/drive/root:/AppTry/provaupload.json:/content";
using (UnityWebRequest www = new UnityWebRequest(url, "PUT"))
{
byte[] dataToSend = new System.Text.UTF8Encoding().GetBytes(myData);
www.uploadHandler = (UploadHandler)new UploadHandlerRaw(dataToSend);
www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
www.SetRequestHeader("Authorization", "Bearer <code>");
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error + " " + www.downloadHandler.text);
}
else
{
Debug.Log("Upload complete! " + www.downloadHandler.text);
}
}
I'm migrating from .NET Core 1.1 to 2.0, and now I have to update my Authentication too.
I'm using OAuth and OpenIddict to .NET Core 2.0
When I'm sending the request to my connect/token I'm getting this:
OpenIddict.Server.OpenIddictServerHandler[0] The token response was
successfully returned: {
"error": "unsupported_grant_type",
"error_description": "The specified 'grant_type' parameter is not
supported."
}.
This is my request method:
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{url}/connect/token");
request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "client_credentials",
["client_id"] = clientId,
["client_secret"] = clientSecret,
["pessoaid"] = pessoaId,
["usuarioid"] = usuarioId,
["conta"] = conta,
["cpfcnpj"] = userDoubleCpf,
["fonteDados"] = fonteDados,
["userIdsLogged"] = userIdsLogged
});
var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
response.EnsureSuccessStatusCode();
var result = JObject.Parse(await response.Content.ReadAsStringAsync());
if (result["error"] != null)
{
throw new InvalidOperationException("An error occurred while retrieving an access token.");
}
return result;
}
My OpenIddictApplications is generated when an application is linked to the user account, so the ClientId and Secret is generated, when a login request is send to my API and retrieve the respective values.
I have folowed the oppeniddict documentation and I have included everything in my Startup.cs
This is my AuthorizationController:
[HttpPost("~/connect/token"), Produces("application/json")]
public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
{
Debug.Assert(request.IsTokenRequest(),
"The OpenIddict binder for ASP.NET Core MVC is not registered. " +
"Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");
if (request.IsClientCredentialsGrantType())
{
// Note: the client credentials are automatically validated by OpenIddict:
// if client_id or client_secret are invalid, this action won't be invoked.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);
if (application == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = "The client application was not found in the database."
});
}
// Create a new authentication ticket.
var ticket = CreateTicket(request, application);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
ErrorDescription = "The specified grant type is not supported."
});
}
I'm generating the AuthenticationTicket and returning this.
Any idea about what might be causing this kind of badrequest when I try to send the request to take my token?
This happens because you do not configure the client credentials flow on you Startup.cs.
See the example: https://github.com/openiddict/openiddict-samples/blob/dev/samples/ClientCredentialsFlow/AuthorizationServer/Startup.cs
Attention for line 52:
// Enable the client credentials flow.
options.AllowClientCredentialsFlow();
I am using Azure Data factory HTTP connector as a linked service to read data from the REST endpoint using basic authentication.
{
"name": "LS_HTTP",
"properties": {
"hubName": "Hub name",
"type": "Http",
"typeProperties": {
"url": "http://*****.azurewebsites.net",
"authenticationType": "Basic",
"gatewayName": "",
"encryptedCredential": "",
"username": "test",
"password": "**********",
"enableServerCertificateValidation": true
}
}
}
Following code snippet is written to fetch the username and password from the headerin my web API
string authHeader = context.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':');
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
if (username == "test" && password == "****")
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
else
{
// no authorization header
context.Response.StatusCode = 401; //Unauthorized
return;
}
When I run Azure data factory pipeline with this setup, I am not able to get username and password from the request header in the web api, basically Authorization header itself is null.
Help me to fetch the username and password passed from my ADF connector service in my web API.
Looking at your definition, you're working with Data Factory v1. I see you configure some properties that are not required for basic authentication.
encryptedCredential, is not required. The documentation states:
Description: Encrypted credential to access the HTTP endpoint. Auto-generated when you configure the authentication information in copy wizard or the ClickOnce popup dialog.
Required: No. Apply only when copying data from an on-premises HTTP server.
gatewayName, is not required since you're not using an on-premises HTTP server
Description: Name of the Data Management Gateway to connect to an on-premises HTTP source.
enableServerCertificateValidation, already defaults to true
Documentation gives this basic example:
{
"name": "HttpLinkedService",
"properties":
{
"type": "Http",
"typeProperties":
{
"authenticationType": "basic",
"url" : "https://en.wikipedia.org/wiki/",
"userName": "user name",
"password": "password"
}
}
}
I'm trying to embed a docusign signature page into a website. but I get this error
Message=Error calling CreateRecipientView: {
"errorCode": "UNKNOWN_ENVELOPE_RECIPIENT",
"message": "The recipient you have identified is not a valid recipient of
the specified envelope."
}
I'm using the .Net nuget client and here's the code I'm using (note I've changed guids and emails)
Authenticate
string userId = "0570b3da-652e-4040-842e-65a0e6fc8133"; // use your userId (guid), not email address
string integratorKey = "cf73e7bb-e05d-4ce9-9cea-ac065dc894ac";
string host = "https://demo.docusign.net/restapi";
ApiClient apiClient = new ApiClient(host);
string username = "my#email.com";
string password = "[password]";
// initialize client for desired environment (for production change to www)
Configuration.Default.ApiClient = apiClient;
// configure 'X-DocuSign-Authentication' header
string authHeader = "{\"Username\":\"" + username + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
Find account id
this was part of the example code
// we will retrieve this from the login API call
string accountId = null;
AuthenticationApi authApi = new AuthenticationApi(apiClient.Configuration);
LoginInformation loginInfo = authApi.Login();
//find the default account for this user
foreach (LoginAccount loginAcct in loginInfo.LoginAccounts)
{
if (loginAcct.IsDefault == "true")
{
accountId = loginAcct.AccountId;
string[] separatingStrings = { "/v2" };
// Update ApiClient with the new base url from login call
apiClient = new ApiClient(loginAcct.BaseUrl.Split(separatingStrings, StringSplitOptions.RemoveEmptyEntries)[0]);
break;
}
}
Create Envelope from a template
EnvelopeDefinition envDef = new EnvelopeDefinition();
TemplateRole tRole = new TemplateRole();
tRole.Email = "recipient#email.com";
tRole.RoleName = "Leaseholder";
tRole.ClientUserId = tRole.Email;
List<TemplateRole> rolesList = new List<TemplateRole> { tRole };
envDef.TemplateRoles = rolesList;
envDef.TemplateId = "2504e3f0-f4d9-4eca-9fd3-3b26cfd6c086";
RecipientViewRequest viewOptions = new RecipientViewRequest()
{
ReturnUrl = "http://localhost:64202/home/winning",
ClientUserId = tRole.Email, // must match clientUserId of the embedded recipient
AuthenticationMethod = "email",
UserName = tRole.Email,
Email = tRole.Email
};
EnvelopesApi envelopesApi = new EnvelopesApi();
var summary = envelopesApi.CreateEnvelope(accountId, envDef);
var receipients = envelopesApi.ListRecipients(accountId, summary.EnvelopeId);
ViewUrl viewUrl = envelopesApi.CreateRecipientView(accountId, summary.EnvelopeId, viewOptions);
return Content($"<h2>hmm</h2><iframe width=\"100%\" height=\"100%\" src=\"{viewUrl.Url}\"/>");
Recipients on the template
Recipients
{
"agents": [],
"carbonCopies": [],
"certifiedDeliveries": [],
"editors": [],
"inPersonSigners": [],
"intermediaries": [],
"recipientCount": "1",
"seals": [],
"signers": [
{
"clientUserId": "recipient#email.com",
"creationReason": "sender",
"deliveryMethod": "email",
"email": "recipient#email.com",
"isBulkRecipient": "false",
"name": "",
"note": "",
"recipientId": "1",
"recipientIdGuid": "52abdeea-2bd6-4108-97b9-170ca27d573a",
"requireIdLookup": "false",
"roleName": "Leaseholder",
"routingOrder": "1",
"status": "created",
"userId": "0570b3da-652e-4040-842e-65a0e6fc8133"
}
]
}
The UNKNOWN_ENVELOPE_RECIPIENT error usually means that one of the following three property values specified for the Recipient within the Envelope doesn't exactly match the corresponding value that's been specified in the Get Recipient View request:
Name
Email
ClientUserId
In your case (based upon the code you posted), I suspect that the UNKNOWN_ENVELOPE_RECIPIENT error is being caused by the fact that the info you've specified for the recipient does not include a value for the Name property -- where as the info you've specified when creating the RecipientViewRequest object does include a value for the UserName property (as it must).
To fix this error, I'd suggest that you try adding this line to the portion of your code when you're specifying information for the TemplateRole object (where "RECIPIENT_NAME" is the first and last name of the recipient).
tRole.Name = "RECIPIENT_NAME;
And then specify the same value for the UserName property of the RecipientViewRequest object:
UserName = "RECIPIENT_NAME",
(The value you specify as RECIPIENT_NAME will be the name that the recipient signs in the doc(s), so you should specify first name / last name of the person, not an email address.)
UPDATE
Re the subsequent RECIPIENT_NOT_IN_SEQUENCE error that you've mentioned in your comment, this error occurs when you call Get Recipient View for a recipient either before the Envelope has been sent or before it's "their turn" in the routing order to receive the Envelope. In your case, I suspect this is occurring because you're not setting the status of the Envelope to sent -- the recipient can't receive/access the Envelope until it's been sent. To resolve this error, set the status of of the Envelope when you're composing the EnvelopeDefinition object:
envDef.Status = "sent";