Email confirmation - strange behavior - asp.net-core

Does anyone have an idea why this is happening to me?
In this case, 'result' is 'Success':
public async Task<IActionResult> TestConfirmInSameRequest(string userId)
{
var user = await this._userManager.FindByIdAsync(userId);
var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);
var result = await this._userManager.ConfirmEmailAsync(user, code);
var newLocation = ...
return Redirect(newLocation);
}
And in this case, 'result' always is 'InvalidToken' (even when I manually copy the original code and test with it)
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
var user = await this._userManager.FindByIdAsync(userId);
var result = await this._userManager.ConfirmEmailAsync(user, code);
var newLocation = ...;
return Redirect(newLocation);
}
protected async Task SendConfirmationEmail(string userId, bool originMobile)
{
var user = await this._userManager.FindByIdAsync(userId);
var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);
var encodedCode = HttpUtility.UrlEncode(code);
var callbackUrl = $"https://.../api/account/confirmemail?userId={userId}&code={encodedCode}";
await this._userService.SendConfirmationEmailAsync(userId, callbackUrl);
}

When sending (SendConfirmationEmail) the e-mail you urlencode the token, but in ConfirmEmail you are not decoding the token.
Encoding it just makes sure it can be used in a URL and no breaking characters are in the URL. However, the token you should validate is not the encoded one, its still the token you got before encoding. In other words; you need to decode the token again so its back to the way it was when it got generated.

Related

ASP.NET Core 3.1 - PostAsync/PostAsJsonAsync method in Integration Test always returns Bad Request

This is my register method inside the AuthController.
[HttpPost(ApiRoutes.Auth.Register)]
public async Task<IActionResult> Register(UserRegistrationRequest request)
{
var authResponse = await _authService.RegisterAsync(request.Email, request.Password);
if (!authResponse.Success)
{
return BadRequest(new AuthFailedResponse
{
Errors = authResponse.Errors
});
}
return Ok(new AuthSuccessResponse
{
Token = authResponse.Token,
RefreshToken = authResponse.RefreshToken
});
}
I'm trying to call this method by using TestClient.PostAsync() method, unfortunately it always returns Bad Request. I've already tried calling the TestClient.PostAsJsonAsync(ApiRoutes.Auth.Register, user) method by importing Microsoft.AspNet.WebApi.Client package, the result is the same.
var user = new UserRegistrationRequest
{
Email = "user1#testtest.com",
Password = "P#ssw0rd1!!!!!"
};
var response = await TestClient.PostAsync(
ApiRoutes.Auth.Register,
new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8)
{
Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
});
You are missing the FromBody attribute from you action parameter. When you are sending json data to a controller that will be part of the request body. You can tell to the controller how to bind the incoming data, in your case from the body. So you code should look like:
public async Task<IActionResult> Register([FromBody]UserRegistrationRequest request)
{
…
}
You could read more about bindings in the official documentation.

Asp.net Core 2.1 HttpClientFactory: second api call is not waiting for first api call's returned result

I encountered an issue using HttpClientFactory. I need to call two web methods from one third party web api.
getOrderNumber.
getShippingLabelFile.
Call #2 depends on #1's result since it needs to pass orderNumber to it e.g.:
await _client.getAsync("http://xxx/api/getLabel?orderNumber=[returnedOrderNumber]&fileType=1")
When I set break-point and debug, it works as expected. Without debugging mode, #2 web method always failed. I have done investigation. If I pass static query parameter like:
http://xxx/api/getLabel?orderNumber=123&fileType=1
it works fine. It seems #2 evaluates the query string and execute api call before orderNumber gives to it. It is very frustrating, can you please shed on some light on this issue?
On Controller:
private readonly ISite1AuthHttpClient _site1HttpClient;
public OrderShippingOrdersController(site1AuthHttpClient)
{
_site1HttpClient=site1AuthHttpClient
}
[HttpGet("{id}")]
public async Task<IActionResult> GetShippingLabel(int id)
{
string token=await _site1HttpClient.GetToken(username.ToString(),password);
string orderNumber=await _site1HttpClient.CreateOrder(Order,token);
if (orderNumber!=null && orderNumber!="")
{
//this API call always failed during runtime. It works on debugging mode.
var streamFile=(MemoryStream)(await _site1HttpClient.getShippingLabel(orderNumber,token));
}
}
HttpClient Type Class:
public interface ISite1HttpClient
{
Task<string> CreateOrder(AueCreateOrder order,string token);
Task<Stream> GetShippingLabel(string orderNumber,string token);
}
public class Site1HttpClient:ISite1HttpClient
{
private readonly HttpClient _client;
public Site1HttpClient(HttpClient httpClient)
{
httpClient.BaseAddress = new Uri("http://abcapi.Site1.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
_client = httpClient;
}
public async Task<string> CreateOrder(AbcCreateOrder order,string token)
{
var jsonInString=JsonConvert.SerializeObject(order);
jsonInString="[ " + jsonInString + " ]";
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",token);
HttpResponseMessage response = await _client.PostAsync(
"api/AgentShipmentOrder/Create", new StringContent(jsonInString, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var contents = await response.Content.ReadAsStringAsync();
AbcOrderCreateResponse abcRes = JsonConvert.DeserializeObject<AbcOrderCreateResponse>(contents);
return abcRes.Message;
}
else
{
var errorResponse = await response.Content.ReadAsStringAsync();
throw new Exception(errorResponse);
}
}
public async Task<Stream> GetShippingLabel(string orderNumber,string token)
{
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",token);
HttpResponseMessage response = await _client.GetAsync("api/GetOrderLabel?orderId="+orderNumber+"&fileType=1");
if (response.IsSuccessStatusCode)
{
Stream streamFile= await response.Content.ReadAsStreamAsync();
return streamFile;
}
else
{
throw new Exception("failed to get label.");
}
}
}
string token = _site1HttpClient.GetToken(username.ToString(),password);
string orderNumber = await _site1HttpClient.CreateOrder(Order,token);
I guess the problem occurs because of first await keyword. When you use await for the first function call (calling an async function), you declare that your program does not need to hold on for the response. So the token variable is used in the second function when it is not set. As you can see above, you should be good to go without the first await for the token variable.

identity framekwork: how to get current login

[HttpPost]
public async Task<IActionResult> Upload(IFormFile files)
{
//var info = await _signInManager.GetExternalLoginInfoAsync();
//var user = await _userManager.FindByIdAsync(User.Identity.GetUserId());
//var user = await _userManager.FindByIdAsync(_userManager.GetUserId(Request.HttpContext.User));
//var user = User.Identity.GetUserId(HttpContext.User); _userManager.GetUserId(Request.HttpContext.User);
//var user1 = await GetCurrentUserAsync();
//var userId = user?.Id;
var filePath = Path.GetTempFileName();
var stream = files.OpenReadStream();
var name = files.FileName;
byte[] fileData = ReadFully(stream);
return Content("Error in uploads");
}
I have this action method. I have created login action whose result is success.
I am trying to get the ID of the current login user but im not able to get that. I have tried 50 ways to do that but failing again and again.
help needed
thanks in adv
I think you forgot to add HttpContext.user
var user = await _userManager.GetUserAsync(HttpContext.User);
if (user == null) return View("Error");

Azure web api Unauthorized 401

I have some code that used to call Azure Scheduler to get a token, then using that token, make restful calls. Works a treat.
So i decided to adopt the code into a new app but this time call my own web api hosted on azure. The API is registered in Active directory I have created a secret key etc. When i initiliaze my static httpclient it fetches a token succesfully.
But when i make a call to the API using the token for auth, the response is a 401 "unauthorized", below is the code.
public static class SchedulerHttpClient
{
const string SPNPayload = "resource={0}&client_id={1}&grant_type=client_credentials&client_secret={2}";
private static Lazy<Task<HttpClient>> _Client = new Lazy<Task<HttpClient>>(async () =>
{
string baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
var client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
await MainAsync(client).ConfigureAwait(false);
return client;
});
public static Task<HttpClient> ClientTask => _Client.Value;
private static async Task MainAsync(HttpClient client)
{
string tenantId = ConfigurationManager.AppSettings["AzureTenantId"];
string clientId = ConfigurationManager.AppSettings["AzureClientId"];
string clientSecret = ConfigurationManager.AppSettings["AzureClientSecret"];
string token = await AcquireTokenBySPN(client, tenantId, clientId, clientSecret).ConfigureAwait(false);
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); //TODO ssmith: const or localization
}
private static async Task<string> AcquireTokenBySPN(HttpClient client, string tenantId, string clientId, string clientSecret)
{
var payload = String.Format(SPNPayload,
WebUtility.UrlEncode(ConfigurationManager.AppSettings["ARMResource"]),
WebUtility.UrlEncode(clientId),
WebUtility.UrlEncode(clientSecret));
var body = await HttpPost(client, tenantId, payload).ConfigureAwait(false);
return body.access_token;
}
private static async Task<dynamic> HttpPost(HttpClient client, string tenantId, string payload)
{
var address = String.Format(ConfigurationManager.AppSettings["TokenEndpoint"], tenantId);
var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
using (var response = await client.PostAsync(address, content).ConfigureAwait(false))
{
if (!response.IsSuccessStatusCode)
{
Console.WriteLine("Status: {0}", response.StatusCode);
Console.WriteLine("Content: {0}", await response.Content.ReadAsStringAsync().ConfigureAwait(false));
}//TODO: start removing tests
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
}
}
}
The above code is the class that creates a httpclient and gets its authorization.
public virtual async Task<T> GetAsync(string apiURL)
{
try
{
_client = await SchedulerHttpClient.ClientTask;
var response = await _client.GetAsync(apiURL);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsAsync<T>().ConfigureAwait(false);
return responseContent;
}
catch (Exception e)
{
return default(T);
}
}
The above code is a quick lift of my old code simply to test if i can get any results. but as stated it returns a 401.
My question is, is my old code to get authorization incorrect?
<add key="ARMResource" value="https://management.core.windows.net/" />
<add key="TokenEndpoint" value="https://login.windows.net/{0}/oauth2/token" />
<add key="BaseAddress" value="https://mysite.azurewebsites.net" />
As suspected, This particular issue was cause by the incorrect "ARMresource" in the case of a web api it required me to change it to the client id.
Source of answer
Seems my issue was the same, however i suspect i may be able to omit the resource entirely from my SPNPayload string.

How to receive a response package from GET request for OneNote API

I'm getting a acknowledgement but no response message (details) i.e. list of notebooks from the OneNote API. Below is my code. I am able to receive the header and JSON details from a POST message but not the GET. I have tried to convert the POST code in order to submit a GET request.
private async void getRequestClick(object sender, RoutedEventArgs e)
{
await GetRequests(true, "test");
}
async public Task<StandardResponse> GetRequests(bool debug, string sectionName)
{
Uri PagesEndPoint1 = new Uri("https://www.onenote.com/api/v1.0/notebooks");
var client = new HttpClient();
//// Note: API only supports JSON return type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//// This allows you to see what happens when an unauthenticated call is made.
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authClient.Session.AccessToken);
}
HttpResponseMessage response;
HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Get, PagesEndPoint1);
response = await client.SendAsync(createMessage);
tbResponse.Text = response.ToString();
return await TranslateResponse(response);
}
private async static Task<StandardResponse> TranslateResponse(HttpResponseMessage response)
{
StandardResponse standardResponse;
if (response.StatusCode == HttpStatusCode.Created)
{
dynamic responseObject = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
standardResponse = new CreateSuccessResponse
{
StatusCode = response.StatusCode,
OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
};
}
else
{
standardResponse = new StandardErrorResponse
{
StatusCode = response.StatusCode,
Message = await response.Content.ReadAsStringAsync()
};
}
// Extract the correlation id. Apps should log this if they want to collcet the data to diagnose failures with Microsoft support
IEnumerable<string> correlationValues;
if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues))
{
standardResponse.CorrelationId = correlationValues.FirstOrDefault();
}
return standardResponse;
}
My POST messages are working OK. I can create a new page etc.
I think you need to change the expected status code from HttpStatusCode.Created to HttpStatusCode.OK for Get requests, since they return a 200 and not a 201. Try doing that in your TranslateResponse method.