How to localize identity error message in .NET 6.0 - c#

I am trying to localize standard identity error messages. I have seen several discussions about this topic. I did manage to create a project and use my own translations and failed on translating standard identity error messages. I decided to create a new project to focus on identity errors. The constructor MultilanguageIdentityErrorDescriber is getting called and returns expected value. When I go to https://localhost:7067/Identity/Account/Register and type "test" into email field standard error "The Email field is not a valid e-mail address." is shown. I appreciate when somebody can guide me into the right directions or send me some links. After a few hours I have decided to ask you guys here. Thanks!
Program.cs
using Localizer.Data;
using Localizer.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddErrorDescriber<MultilanguageIdentityErrorDescriber>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
MultilanguageIdentityErrorDescriber.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Localization;
public class MultilanguageIdentityErrorDescriber : IdentityErrorDescriber
{
private readonly IStringLocalizer<SharedResource> _localizer;
public MultilanguageIdentityErrorDescriber(IStringLocalizer<SharedResource> localizer)
{
_localizer = localizer;
// ckecking identityError.Description which returns expected value
var identityError = new IdentityError();
identityError = this.InvalidEmail("email#email.com");
}
public override IdentityError DuplicateEmail(string email)
{
return new IdentityError()
{
Code = nameof(DuplicateEmail),
Description = string.Format(_localizer["Email {0} is already taken."], email)
};
}
public override IdentityError DuplicateUserName(string userName)
{
return new IdentityError()
{
Code = nameof(DuplicateEmail),
Description = string.Format(_localizer["Email {0} is already taken."], userName)
};
}
public override IdentityError InvalidEmail(string email)
{
return new IdentityError
{
Code = nameof(InvalidEmail),
Description = string.Format(_localizer["Email '{email}' is invalid."], email)
};
}
}

I have the same problem in my project and I also couldn't find a way to translate the Identity error messages, so I made a workaround that didn't look pretty but it solve my problem, I made a Class with a method that checks the error code and sets a custom messagem, so I can not only translate but also define my own error messages. I did it to translate to Brazilian portuguese,
here is the code:
public class TranslateIdentityErrors
{
public string TranslateErrorMessage(string codeError)
{
string message = string.Empty;
switch (codeError)
{
case "DefaultError":
message = "Um erro desconhecido ocorreu.";
break;
case "ConcurrencyFailure":
message = "Falha de concorrência otimista, o objeto foi modificado.";
break;
case "InvalidToken":
message = "Token inválido.";
break;
case "LoginAlreadyAssociated":
message = "Já existe um usuário com este login.";
break;
case "InvalidUserName":
message = $"Este login é inválido, um login deve conter apenas letras ou dígitos.";
break;
case "InvalidEmail":
message = "E-mail inválido.";
break;
case "DuplicateUserName":
message = "Este login já está sendo utilizado.";
break;
case "DuplicateEmail":
message = $"Este email já está sendo utilizado.";
break;
case "InvalidRoleName":
message = "Esta permissão é inválida.";
break;
case "DuplicateRoleName":
message = "Esta permissão já está sendo Utilizada";
break;
case "UserAlreadyInRole":
message = "Usuário já possui esta permissão.";
break;
case "UserNotInRole":
message = "Usuário não tem esta permissão.";
break;
case "UserLockoutNotEnabled":
message = "Lockout não está habilitado para este usuário.";
break;
case "UserAlreadyHasPassword":
message = "Usuário já possui uma senha definida.";
break;
case "PasswordMismatch":
message = "Senha incorreta.";
break;
case "PasswordTooShort":
message = "Senha muito curta.";
break;
case "PasswordRequiresNonAlphanumeric":
message = "Senhas devem conter ao menos um caracter não alfanumérico.";
break;
case "PasswordRequiresDigit":
message = "Senhas devem conter ao menos um digito ('0'-'9').";
break;
case "PasswordRequiresLower":
message = "Senhas devem conter ao menos um caracter em caixa baixa ('a'-'z').";
break;
case "PasswordRequiresUpper":
message = "Senhas devem conter ao menos um caracter em caixa alta ('A'-'Z').";
break;
default:
message = "Um erro desconhecido ocorreu.";
break;
}
return message;
}
}
}
To use this method i go to where the error messages are passed to modelstate and change the code from this:
var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded)
{
foreach (var error in changePasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
to this:
var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded)
{
TranslateIdentityErrors translateErrors = new();
foreach (var error in changePasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, translateErrors.TranslateErrorMessage(error.Code));
}
return Page();
}

Related

Angular requests to ASP.NET return "Error Unknown" when under SSL/TLS certificate

I've walked through this trouble and I've still didn't found any answer:
My Angular application sends a bunch of HTTP requests to asp.net. Asp.net process the request ( token check, etc.. ) and returns the data as ordered.
Thing is, on IIS, I've added SSL/TLS certificate from Let's Encrypt and the application never worked again.
Strange behaviours I've notivced
Only login method works. All request that follow, return "Unknown Error - Status Code 0"
Asp.net has an interceptor that filters every request to check the token. If I send the Authorization header, the application fails. If I don't, asp.net returns 404 error stating that token doesnt exists on the database ( as it shoud )
In Postman, the requests works 100% ( even the check of authenticity of the token)
If I remove either the angular interceptor and the middleware in asp.net AND remove the SSL cert. the application works
Chrome throws the "net::ERR_SPDY_PROTOCOL_ERROR" exception.
I've been over my head for two days and found no answer. Looked up on StackOverflow, IIS foruns, Angular foruns, .Net foruns... Nothing
Here some code:
Angular Interceptor
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Filtrar apenas pedidos feitos à API
if(req.url.match("\\api")) {
let newRequest = req.clone({
headers: new HttpHeaders({
'Content-Type':'application/json',
'Authorization':this.cookieService.get('at')
})
});
return next.handle(newRequest);
} else {
return next.handle(req);
}
}
Asp.NET Middleware
public Task Invoke(HttpContext context) {
// Check if request is redirected to ".../api/exemplo/xyx"
// To exclude the 'login' request
if (context.Request.Path.Value.StartsWith("/api")) {
// Check if request is NOT an OPTIONS
if(!context.Request.Method.Equals("OPTIONS")){
// Check for header
string auth = context.Request.Headers["Authorization"].ToString();
FbConnectionStringBuilder csb = new FbConnectionStringBuilder {
DataSource = _appSettings.DataSource,
Port = _appSettings.Port,
Database = _appSettings.Database,
UserID = _appSettings.UserID,
Password = _appSettings.Password,
ServerType = FbServerType.Default
};
// Open db
FbConnection db = new FbConnection(csb.ToString());
db.Open();
// Get the expiration date of token
string query = "SELECT DT_REVOG FROM ORGANIG_TOKEN WHERE TOKEN = #auth";
DateTime now = DateTime.UtcNow;
DateTime DateRevogToken;
try
{
DateRevogToken = db.QuerySingle<DateTime>(query, new { auth });
db.Close();
if (now >= DateRevogToken)
{
// Expired
string deleteQuery = "DELETE FROM ORGANIG_TOKEN WHERE TOKEN = #auth";
db.Execute(deleteQuery, new { auth });
context.Response.StatusCode = 401;
context.Response.WriteAsync("A token não é válida");
return Task.CompletedTask;
}
else
{
// Is valid
return _next(context);
}
} catch(Exception e) {
context.Response.StatusCode = 404;
context.Response.WriteAsync("Ocorreu um erro na verificação da token: " + e.Message);
return Task.CompletedTask;
}
}
else {
//It's a OPTIONS request. Ignore
return _next(context);
}
}
else {
// Login request. Ignore
return _next(context);
}
}
}
Login request (asp.net)
[Route("auth/gerar_token")]
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> GerarToken([FromBody] Client c)
{
// Conexão á base de dados Firebird
FbConnectionStringBuilder csb = new FbConnectionStringBuilder
{
DataSource = _appSettings.DataSource,
Port = _appSettings.Port,
Database = _appSettings.Database,
UserID = _appSettings.UserID,
Password = _appSettings.Password,
ServerType = FbServerType.Default
};
Client client = new Client();
string login = c.login;
string pass = c.pass;
string hashedPass = null;
string responseMessage;
// Hash da password do client
using (MD5 md5Hash = MD5.Create()) { hashedPass = GetMd5Hash(md5Hash, pass); }
using (var db = new FbConnection(csb.ToString())) {
string token;
try {
await db.OpenAsync();
// Query de login
string sql = #"SELECT CD, NOME, RAMO_ACT, DESIGN, EMAIL, LOGIN, MORAD
FROM ORGANIG WHERE LOGIN = #login AND PASS = #hashedPass";
client = await db.QuerySingleAsync<Client>(sql, new { login, hashedPass });
try {
int cd_organig = client.cd;
token = GenerateRefreshToken();
DateTime dt_cria = DateTime.UtcNow;
DateTime dt_revog = dt_cria.AddHours(4);
DateTime dt_inicio = DateTime.UtcNow;
string sql_token = #"INSERT INTO ORGANIG_TOKEN(TOKEN, CD_ORGANIG, DT_CRIA, DT_REVOG) VALUES (#token, #cd_organig, #dt_cria, #dt_revog)";
db.Execute(sql_token, new { token, cd_organig, dt_cria, dt_revog });
string sql_sessao = #"INSERT INTO ORGANIG_SESSAO(CD_ORGANIG, DT_INICIO, TOKEN, DT_REVOG_TOKEN) VALUES (#cd_organig, #dt_inicio, #token, #dt_revog)";
db.Execute(sql_sessao, new { cd_organig, dt_inicio, token, dt_revog });
}
catch (Exception e) {
JObject serverErroResponse = new JObject {
{ "Ocorreu um erro no servidor. Detalhes: ", e.Message }
};
db.Close();
return StatusCode(500, serverErroResponse);
}
JObject response = new JObject {
{ "token", token },
{ "cd", client.cd },
{ "nome", client.nome }
};
db.Close();
return Ok(response);
}
catch (Exception e) {
if(e.Message.Equals("Sequence contains no elements")) {
responseMessage = "Credenciais inválidas. Por favor, tente novamente";
} else {
responseMessage = "Ocorreu um erro no servidor. Detalhes: " + e.Message;
}
JObject serverErrorResponse = new JObject {
{ "message", responseMessage }
};
db.Close();
return StatusCode(500, serverErrorResponse);
}
} // using (var db = new FbConnection(csb.ToString()))
}
Example of request that doesnt work
[Route("api/build_organig/{cd}")]
[HttpGet]
public IActionResult BuildOrganig(int cd)
{
// Conexão á base de dados Firebird
FbConnectionStringBuilder csb = new FbConnectionStringBuilder {
DataSource = _appSettings.DataSource,
Port = _appSettings.Port,
Database = _appSettings.Database,
UserID = _appSettings.UserID,
Password = _appSettings.Password,
ServerType = FbServerType.Default
};
// Abrir conexão á base de dados
FbConnection db = new FbConnection(csb.ToString());
db.Open();
// Query para retornar os dados do procedure para uma lista
List<BuildOrganig> buildOrganigList = new List<BuildOrganig>();
buildOrganigList = db.Query<BuildOrganig>("SELECT CD, CD_BASE, NOME FROM BUILD_ORGANIG(#cd) ORDER BY NIVEL", new { cd }).ToList();
if (buildOrganigList.Count == 0) {
JObject emptyResponse = new JObject {
{ "count", buildOrganigList.Count },
{ "message", "Organigrama não existente" }
};
db.Close();
return StatusCode(404, emptyResponse);
}
db.Close();
return StatusCode(200, buildOrganigList);
}
Here are some screenshots of postman and the browser
If you need more info, just state in the comments.
Thanks
I had similar issues with Chrome and custom auth headers giving me a SPDY error.
I changed the name of my Authorization header to "X-Custom-Auth" and gave the OPTIONS a special response like this:
response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
// Important: copy back the expected allowed headers
response.Headers["Access-Control-Allow-Headers"] = request.Headers["Access-Control-Request-Headers"];
response.AddHeader("Access-Control-Max-Age", "1728000");
response.Flush();
response.End();
You may also need to add your custom auth header name to web config or CORS config.
Hope it also applies in your case.

Return ScanPage Xamarin

I have a button with open a scan (as a modal). When I scan a QRCode i have a display alert with 2 buttons. When I click on "no" I want to return on my scan and not in my page (listPeoplePage).
So I have a button ScanClicked (when I open the scan)
private async Task BtnScanClicked(object sender, EventArgs e)
{
// Ouverture de la page de scan
scanPage = DependencyService.Get<IScanPage>(); // new ZXingScannerPage();
if (scanPage.scannerPage.IsScanning)
return;
scanPage.scannerPage.IsScanning = true;
if (scanPage.scannerPage.Parent == null)
{
// On affiche la page
await Navigation.PushModalAsync(scanPage.scannerPage); //.PushAsync(scanPage.scannerPage);
}
// Le check des résultats
scanPage.scannerPage.OnScanResult += (result) =>
{
// Pour éviter de le faire tant que le client n'a pas validé
if (scanPage.scannerPage.IsScanning == false)
return;
// On stoppe le scan
scanPage.scannerPage.IsScanning = false;
// On retire la page et on montre le résultat
Device.BeginInvokeOnMainThread(async () =>
{
// On essaye de récupérer le code IdA09 si il existe et on appelle le WS
string paramA09 = getParameterByName(result.Text, "IdA09");
if (!string.IsNullOrEmpty(paramA09))
{
//await DisplayAlert("Scanned barcode", paramA09, "OK");
await SendPresenceAck(paramA09,sender,e); //, this.idPrestation);
}
else
{
// Message d'erreur
await this.DisplayAlert("Attention", "Erreur de la validation d'un invité par QR Code.", "Cancel");
}
await Navigation.PopModalAsync(); //.PopAsync();
});
};
}
And there is a method SendPresenceAck when I have scan a QrCode
private async Task SendPresenceAck(string paramA09, object sender, EventArgs e) //, int? idPrestation)
{
int idParticipant;
if (!int.TryParse(paramA09, out idParticipant))
{
//await this.ShowAlert("Attention", "Problème de lecture du QR Code.");
await this.DisplayAlert("Attention", "Problème de lecture du QR Code.", "Yes","No");
return;
}
// On appelle le WS pour signifier la présence
// On passe par validateService
// On prépare la validation de la présence
var validateService = new ValidatePresenceService(this.Token);
// On ajoute la ligne à valider
var validate = validateService.AddNewPresence(idParticipant, this.idPrestation, true);
// On déclenche l'envoi au WS (si besoin)
if (validate != null)
{
// On envoie uniquement en cas de connexion
if (!Global.GetSettingsBool(TypeSettings.IsHorsConnexion))
{
//await validateService.SendAll();
// Attention : si participant déjà enregistré : erreur 403
try
{
await validateService.Send(await validate);
await this.DisplayAlert("OK", "Le billet est validé.", "OK");
}
catch (WebException ex)
{
HttpWebResponse objresponse = ex.Response as HttpWebResponse;
if (objresponse.StatusCode == HttpStatusCode.Forbidden)
{
// 403 : le participant a déjà été enregistré aujourd'hui
// Message d'erreur
await this.DisplayAlert("Attention", "Le billet a déjà été enregistré, le numéro du billet a déjà été scanné auparavant.", "Yes", "No");
return;
}
else if (objresponse.StatusCode == HttpStatusCode.NotFound)
{
// 404 : billet non valide
var alert = await this.DisplayAlert("Attention", "Le billet n'est pas valide.", "Yes","No");
if (alert==true)
return;
else
{
}
}
else if (objresponse.StatusCode == HttpStatusCode.Unauthorized)
{
// 401 : impossible d'identifier le numéro du billet
var alert = await this.DisplayAlert("Attention", "Impossible d'identifier le numéro du billet, veuillez vérifier les informations de celui ci.", "Yes", "No");
if (alert==true)
return;
else
{
Debug.WriteLine(alert);
}
}
}
catch (Exception exception)
{
// Erreur
await this.DisplayAlert("Attention", exception.Message, "Yes", "No");
return;
}
}
else
{
// Hors connexion : on vérifie juste si l'utilisateur n'est pas déjà présent dans la table SQL
// Attention : si pas de prestation : on a le droit d'enregistrer plusieurs fois la présence
// Si il y a une prestation, en revanche, on doit vérifier qu'il n'est pas déjà inscrit
if (validate.Result.IdPrestation.HasValue &&
validateService.IsInscriptionAlreadyRecorded(await validate))
{
// Déjà trouvé : message d'erreur
await this.DisplayAlert("Attention", "Le participant a déjà été enregistré.", "Yes", "No");
return;
}
}
}
else
{
// Pb à l'insertion des données ??
}
//return;
await BtnScanClicked(sender, e);
}
So I want, on my scan to click on a button to return on a scan for scan an other QrCode. A sort of a button "do you want scan an other time?"
Edit: For the moment the only important message is `"await this.DisplayAlert("Attention", "Problème de lecture du QR Code.", "Yes","No");
In English ("Alert", Problem to read QR Code." "Yes", "No");
I try to call again at the end of the SendPresenceAck function but it doesn't work.
For the moment if you answer "yes" or "no" it do nothing. I want to return on scan if you answer "yes" and return to the page if you answer "no".
Might need to see more code, but you are always popping your scanner page at the end of the OnScanResult by calling:
await Navigation.PopModalAsync();
at the end of the OnScanResult method, so no matter what you do in SendPresenceAck when you return from that method, you are popping the modal scanner page.
The non-english (french?) text makes it hard for me to know which alert is asking if the user wants to scan another code, but regardless no matter what they respond, the page will be popped.
Oh, wait, it looks like you have some recursion going on? i.e. BtnScanClicked calls SendPresenceAck and SendPresenceAck calls BtnScanClicked at the end... I'd have to dig though all of your logic to see if this may be an issue, but again that is hard because of the non-english language makes it hard for me to follow code flow after user responses to the multiple alerts.

Listview bugs after add 9 items

I'm having some trouble in my C# program.
After adding 9 items, the programs bugs, when im trying to add the 10th item, it only shows blank spaces.
private void btnConfirmar_Click(object sender, EventArgs e)
{
int NumeroUtente;
if (string.IsNullOrEmpty(txtNomeUtente.Text) || string.IsNullOrEmpty(txtTelefoneUtente.Text) || string.IsNullOrEmpty(txtEmailUtente.Text) || string.IsNullOrEmpty(cbbPulseira.Text))
{
MessageBox.Show("Não podem existir campos vazios!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
// Utentes na Fila de Atendimento
if (ListasFilas.FilaAtendimento.Count == 0)
MessageBox.Show("Erro: Não existem utentes na fila!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
// Utente repetido
if (txtNumeroUtente.Enabled == true && LV_Repetido(Convert.ToInt32(txtNumeroUtente.Text)) == true)
MessageBox.Show("Erro: Utente repetido!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
{
// Cria novo utente
if (NovoUtente == true)
{
// Nº Utente
NumeroUtente = Atribui_Num_Utente();
// Adiciona à ListaUtentes
ListasFilas.ListaUtentes.Add(new Utente(NumeroUtente, txtNomeUtente.Text, Convert.ToInt32(txtTelefoneUtente.Text), txtEmailUtente.Text));
//switch (cbbPulseira.Text)
//{
// case "Verde": ListasFilas.FilaAtVerde.Enqueue(NumeroUtente); break;
// case "Amarela": ListasFilas.FilaAtAmarelo.Enqueue(NumeroUtente); break;
// case "Vermelha": ListasFilas.FilaAtVermelho.Enqueue(NumeroUtente); break;
// case "Roxa": ListasFilas.FilaAtRoxo.Enqueue(NumeroUtente); break;
//}
// Atribui número
//NumeroUtente = Atribui_Num_Utente();
}
// Utente existente
else
{
NumeroUtente = Convert.ToInt32(txtNumeroUtente.Text);
}
// Bug encontrado
if(lblSenha.Text == "10")
MessageBox.Show("Bug: Quando chega à senha 10 não mostra os campos na listview!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
// Adiciona à listview
int cntItems = lvUtentes.Items.Count;
lvUtentes.Items.Add(lblSenha.Text); // Senha
lvUtentes.Items[cntItems].SubItems.Add(NumeroUtente.ToString()); // Nº
lvUtentes.Items[cntItems].SubItems.Add(txtNomeUtente.Text); // Nome
lvUtentes.Items[cntItems].SubItems.Add(cbbPulseira.Text); // Fila Cor
// Adiciona à Fila Cores
switch (cbbPulseira.Text)
{
case "Verde": ListasFilas.FilaAtVerde.Enqueue(NumeroUtente); break;
case "Amarela": ListasFilas.FilaAtAmarelo.Enqueue(NumeroUtente); break;
case "Vermelha": ListasFilas.FilaAtVermelho.Enqueue(NumeroUtente); break;
case "Roxa": ListasFilas.FilaAtRoxo.Enqueue(NumeroUtente); break;
}
// Próxima senha
lblSenha.Text = (Convert.ToInt32(lblSenha.Text) + 1).ToString();
ListasFilas.FilaAtendimento.Dequeue(); // Retira o próximo utente da fila
Im not seeing where is the problem, when i try to debug, watching it code by code it works, but when add's to the listview, i just got blank spaces.
Thank you.
EDIT: After some tests i figured out that it bugs when:
lblSenha.text passes from 9 to 10.
lblSenha.text passes from 99 to 100.
When lblsenha.text starts at 10 doesnt bug until 99.

How does OAuth Work in mvc4 C#

I'm using Oauth to get users to register through Facebook etc.
I got all the dlls. but how does it work ?
This is a code i found on the internet but it doesn't work. Any ideas how it works?.. I'm lost :/
Thanks for reading this!
using DotNetOpenAuth.Messaging;
public ActionResult LogOn()
{
var openid = new OpenIdRelyingParty();
IAuthenticationResponse response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
FormsAuthentication.RedirectFromLoginPage(
response.ClaimedIdentifier, false);
break;
case AuthenticationStatus.Canceled:
ModelState.AddModelError("loginIdentifier",
"Login was cancelled at the provider");
break;
case AuthenticationStatus.Failed:
ModelState.AddModelError("loginIdentifier",
"Login failed using the provided OpenID identifier");
break;
}
}
return View();
}
[System.Web.Mvc.AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string loginIdentifier)
{
if (!Identifier.IsValid(loginIdentifier))
{
ModelState.AddModelError("loginIdentifier",
"The specified login identifier is invalid");
return View();
}
else
{
var openid = new OpenIdRelyingParty();
IAuthenticationRequest request = openid.CreateRequest(
Identifier.Parse(loginIdentifier));
// Require some additional data
request.AddExtension(new ClaimsRequest
{
BirthDate = DemandLevel.NoRequest,
Email = DemandLevel.Require,
FullName = DemandLevel.Require
});
return request.RedirectingResponse.AsActionResult();
}
}

DotNetOpenId - Open Id get some data

I'm using OpenId on a new website and am trying to get some basic information about the user, see the code below. Why is the following allways null?
var myData = response.GetExtension<ClaimsResponse>();
And the main code
[System.Web.Mvc.AcceptVerbs(HttpVerbs.Get)]
public ActionResult LogOn()
{
var openid = new OpenIdRelyingParty();
IAuthenticationResponse response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
FormsAuthentication.RedirectFromLoginPage(
response.ClaimedIdentifier, false);
var myData = response.GetExtension<ClaimsResponse>();
break;
case AuthenticationStatus.Canceled:
ModelState.AddModelError("loginIdentifier",
"Login was cancelled at the provider");
break;
case AuthenticationStatus.Failed:
ModelState.AddModelError("loginIdentifier",
"Login failed using the provided OpenID identifier");
break;
}
}
return View("Register");
}
[System.Web.Mvc.AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string loginIdentifier)
{
if (!Identifier.IsValid(loginIdentifier))
{
ModelState.AddModelError("loginIdentifier",
"The specified login identifier is invalid");
return View();
}
else
{
var openid = new OpenIdRelyingParty();
IAuthenticationRequest request = openid.CreateRequest(
Identifier.Parse(loginIdentifier));
// Require some additional data
request.AddExtension(new ClaimsRequest
{
Email = DemandLevel.Request,
FullName = DemandLevel.Request
});
return request.RedirectingResponse.AsActionResult();
}
}
http://www.dotnetopenauth.net/developers/help/the-axfetchassregtransform-behavior/

Categories

Resources