Claim type Error.Not getting the Email.Returning Null
This is my AppUser Class:
public class AppUser
{
public int Id { get; set; }
public string email { get; set; }
public string userFirstName { get; set; }
public string userLastName { get; set; }
}
Now if I Claim User by this Commands
var userEmail = User.FindFirstValue(ClaimTypes.Email)
var userEmail = User.FindFirstValue(ClaimTypes.Name)
returns No Content/Null, But if I Claim this command,
var userEmail = User.FindFirstValue(ClaimTypes.NameIdentifier)
returns userFirstName of AppUser Class,even not the ID.
Why these is behaving like this?I am using asp.net 5.0.1.
Specially I want to get the email of the user. How can I do it ?
See also questions close to this topic
-
Huge amount of logon attempts when loading a page (without cache)
I notice in the Performance Monitor of Windows Server 2012 that there are spikes in logon attempts per second under Web Service -> Logon Attempts/sec. These spikes go from about 0 to 50.
I've traced this down to a page refresh. Loading a page with no cache that is. An average page load does about 50 requests (images, scripts, etc). Now apparently these 50 requests are shown as logon attempts.
Is this normal?
Note that this page does not require the visitor to be logged in.
-
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3\
When warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
No XML encryptor configured. Key {e43b756a-2818-4898-8730-5e8e0f230be7} may be persisted to storage in unencrypted form.
info: IdentityServer4.Startup[0]
Starting IdentityServer4 version 4.1.1+cebd52f5bc61bdefc262fd20739d4d087c6f961f
info: IdentityServer4.Startup[0]
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation.
info: IdentityServer4.Startup[0]
Using the default authentication scheme Identity.Application for IdentityServer
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://[::]:8081
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://[::]:8080
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /app
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token
info: IdentityServer4.AspNetIdentity.ResourceOwnerPasswordValidator[0]
Credentials validated for username: muthu
info: IdentityServer4.Validation.TokenRequestValidator[0]
Token request validation success, {
"ClientId": "sdgfsdsgsdg",
"ClientName": "Swagger UI",
"GrantType": "password",
"Scopes": "api",
"AuthorizationCode": "********",
"RefreshToken": "********",
"UserName": "sample",
"Raw": {
"grant_type": "password",
"username": "sample",
"password": "REDACTED"
}
}
fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3]
Exception occurred while processing message.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'http://*:8080/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
fail: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[0]
IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'http://*:8080/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler.HandleAuthenticateAsync()
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[7]
Bearer was not authenticated. Failure message: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[12]
AuthenticationScheme: Bearer was challenged.
-
ASP.NET using return RedirectToAction(" ", " ") how to use this to redirect to a cshtml
I can not find a useable tutorial that explains how to redirect using REdirectToAction. can someone share a link that that explains ALL the steps needed to use this? I think I am having a hard time understanding how the parameters are given can find an HTML file with a model in the parameter? or is it a controller? I am very lost on how they communicate. please someone if you can help.
-
NullReferenceException in array of objects
I'm working on a program in c# in which I've got an array of objects of a class. I've got a constructor in the class that should give the attached string a value of "" to make sure they're empty so information can be passed in easily. I then have the array created like so:
participants[8][8] grid = new participants[8][];
But I'm being thrown a NullReferenceExcetption error. Here is my code for your reference.
using System; namespace TreasurehuntCsharp { class square { public string strX = ""; public int y = 0; public int x = 0; } class participants { public string name = ""; public string contact = ""; public participants() { name = ""; contact = ""; } } class Program { //Method for user to choose a square static void Input(square Coord) { //Variables bool correct = false; //Inputs Console.WriteLine("Please enter the coordinates of the square you would like to select: \r\n"); do { //X coordinate Console.WriteLine("X: "); Coord.strX = Console.ReadLine().ToLower(); //Convert letter to array coordinate switch (Coord.strX) { case "a": Coord.x = 0; correct = true; break; case "b": Coord.x = 1; correct = true; break; case "c": Coord.x = 2; correct = true; break; case "d": Coord.x = 3; correct = true; break; case "e": Coord.x = 4; correct = true; break; case "f": Coord.x = 5; correct = true; break; case "g": Coord.x = 6; correct = true; break; case "h": Coord.x = 7; correct = true; break; default: Console.WriteLine("Please enter a letter from A to H"); correct = false; break; } } while (correct != true); correct = false; do { //Y coordinate Console.WriteLine("Y: "); Coord.y = Convert.ToInt32(Console.ReadLine()); if (Coord.y >= 1 && Coord.y <= 7) { correct = true; } else { Console.WriteLine("Please input an integer value from 1 to 7."); correct = false; } } while (correct != true); } static void ParticipantDetails(participants User) { Console.WriteLine("Please input your name and Contact number: "); //User name input Console.WriteLine("Name: "); User.name = Console.ReadLine(); //User contact number input Console.WriteLine("Number: "); User.contact = Console.ReadLine(); } static void Main(string[] args) { //Objects square Coord = new square(); participants User = new participants(); //Initialise 2D array participants[][] grid = new participants[8][]; //Variables bool correct = false; do { //Methods Input(Coord); ParticipantDetails(User); //Input data to array if (grid[Coord.x][Coord.y].name == "" && grid[Coord.x][Coord.y].contact == "") { grid[Coord.x][Coord.y].name = User.name; grid[Coord.x][Coord.y].contact = User.contact; Console.WriteLine(grid[Coord.x][Coord.y]); correct = true; } else { Console.WriteLine("That square is already filled. Please try again."); correct = false; } } while (correct == false); } }
-
Cant find sprite
So I have been creating the inventory in my game, I have been following the tutorial, https://www.youtube.com/watch?v=2WnAOV7nHW0 Where I get stuck at 8:40,
I am getting a null error, NullReferenceException: Object reference not set to an instance of an object
At this line of code
Image image = itemSlotRectTransform.Find("image").GetComponent<Image>();
This is the complete code, from the script
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UI_Inventory : MonoBehaviour { private Inventory inventory; private Transform itemSlotContainer; private Transform itemSlotTemplate; public void Awake() { itemSlotContainer = transform.Find("itemSlotContainer"); itemSlotTemplate = itemSlotContainer.Find("itemSlotTemplate"); } public void SetInventory (Inventory inventory) { this.inventory = inventory; RefreshInventoryItems(); } private void RefreshInventoryItems() { int x = -1; int y = 1; float itemSlotCellSize = 255f; foreach (Item item in inventory.GetItemList()) { RectTransform itemSlotRectTransform = Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<RectTransform>(); itemSlotRectTransform.gameObject.SetActive(true); itemSlotRectTransform.anchoredPosition = new Vector2(x * itemSlotCellSize, y * itemSlotCellSize); **Image image = itemSlotRectTransform.Find("image").GetComponent<Image>();** image.sprite = item.GetSprite(); x++; if (x > 4) { x = 0; y++; } } } }
This is the photo of my inspector where the sprites, are attached to
-
NULLReferenceException for a selected drop-down value in an asp.net core mvc application using Mailkit
I am working on an asp.net core 5.0 MVC application, I have used Mailkit Nuget package to send an email to the client after creating a record with all its answers. I have put the code related to the Mailkit inside the Create(Post) method but after creating and sending email I am getting System.NullReferenceException in my Mailkit code part for one of my fields called Product Type when I write it like sale.ProductType.ProductTypeDesc which is basically a drop-down and has a look-up table and so a foreign key to the main table(Sale). but it is working with sale.ProductTypeId which is not something that I want. Can anyone give me solution?
Here are my models:
using System;
using System.Collections.Generic;
#nullable disable
namespace Sale_app.Models
{
public partial class Sale { public int SaleId { get; set; } public string ProductName { get; set; } public string ProductTypeId { get; set; } public virtual ProductType ProductType { get; set; } }
}
using System;
using System.Collections.Generic;
#nullable disable
namespace Sale_app.Models
{ public partial class ProductType
{ public ProductType() { Sales = new HashSet<Sale>(); } public int ProductTypeId { get; set; } public string ProductTypeDesc { get; set; } public virtual ICollection<Sale> Sales { get; set; } }
}
and these are Create methods in my Controller:
//Get Sale
public IActionResult Create()
{ ViewBag.ProductTypeList = _context.ProductType.ToList(); return View(); }
[HttpPost]
[ValidateAntiForgeryToken] public IActionResult Create([Bind("SaleId,ProductTypeId,ProductName")] Sale sale) { if (ModelState.IsValid) { try { _context.Add(sale); _context.SaveChanges(); //instantiate a new MimeMessage var message = new MimeMessage(); //Setting the To e-mail address message.To.Add(new MailboxAddress("E-mail Recipient Name", "an email address comes here")) //Setting the From e-mail address message.From.Add(new MailboxAddress("Sale Form " + "Response", "an email address comes here")); //E-mail subject message.Subject = "Sale Form"; //E-mail message body message.Body = new TextPart(TextFormat.Html) { Text = "<b>SaleId:</b> " + sale.SaleId + "<br/>" + "<b>ProductName:</b> " + sale.ProductName + "<br/>" + "<b>ProductType</b>: " + sale.ProductType.ProductTypeDecs }; //Configure the e-mail using (var emailClient = new SmtpClient()) { emailClient.Connect("smtp.gmail.com", 587, false); emailClient.Authenticate("an email address comes here", "a password comes here"); emailClient.Send(message); emailClient.Disconnect(true); } return RedirectToAction(nameof(Index)); } catch (Exception ex) { ModelState.Clear(); ViewBag.Message = $" Oops! We have a problem here {ex.Message}"; } } return View(sale); }
-
Firebase firestore rules with custom claims
I can't get these firebase custom claims rules to work, and while I'm learning how to debug and write unit tests using the firestore and auth emulators and mocha, the docs seem out of date (the instruction video certainly is).
I have three different types of user: admin, coach and customer, and this is the behaviour I want:
- admin: can read and write anything
- coach: can create new users and docs (but not read, update or delete them)
- customer: can see docs named with their uid
each type of user has a custom claims token ie: { admin: true }
My firestore rules are as follows:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.auth.token.admin == true; allow create: if request.auth.token.coach == true; } match /sessions/{userId} { allow get: if request.auth.token.customer == true && request.auth.uid == userId; } } }
Current behaviour is:
- admin users can see all docs, but coaches can't
- coaches can create users
- Document creation is failing for everybody
- customer users can't see their docs, but atm they are not being created
This function creates new customers by calling the createUser firebase function, then it should save a document with the new user uid as the doc name:
const sendInformationHandler = () => { const customerEmailCurrent = customerEmail.current.value const customerPassword = "newpassword" if (checkUserEmailExists(customerEmailCurrent)) { createUser( { email: customerEmailCurrent, password: customerPassword } ).then(function(user) { firebase .firestore() .collection('sessions') .doc(user.data.uid).set( {...context.state} ).then(() => { console.log("DATA SAVED SUCCESSFULLY!") }).then(() => { dispatch({ type: refreshContextFromCache, payload: INITIAL_CONTEXT}) }).then(() => { push('/'); }) }).catch(err => console.log("AN ERROR OCCURRED", err)) } else { console.log("EMAIL ALREADY EXISTS!!!!!!") } };
My cloud function to create user roles is:
exports.createUser = functions.https.onCall((data) => { return admin.auth().createUser(data) .then(function (userRecord) { // See the UserRecord reference doc for the contents of userRecord. console.log('Successfully created new user:', userRecord.uid); return userRecord; }) .catch(function (error) { console.log('Error creating new user:', error); return error; }); });
And that function triggers a function to grant user roles like so (here set to create customers):
exports.grantUserRole = functions.auth.user().onCreate((user) => { let uid = user.uid; // Check if user meets role criteria. if (user.customClaims && user.customClaims.customer === true) { return null; } if (user.email) { const customClaims = { customer: true }; // Set custom user claims on this newly created user. return admin.auth().setCustomUserClaims(user.uid, customClaims) .then(() => { return admin.auth().getUser(uid); }) .then(userRecord => { console.log(uid); if (userRecord.customClaims) { console.log(userRecord.customClaims.customer); } }) .catch(error => { console.log(error); return null; }); } });
What is happening? Why can't even admin users create docs?
-
How to add new claims to claim array using foreach loop in C#?
I want to add new claims to a claim array in a foreach loop. How to do that?
//userRoles is a list of string contains roles. var userRoles = _repository.GetRolesOfUser(username); var claim = new[] { new Claim("username", username) }; //I want to add new claims to claim like below. //When I put Add I am getting error like this // "Claim[] doesn't contain definition for Add." foreach(var userRole in userRoles) { claim.Add(new Claim("roles", userRole)); }
What I want at the end is something like this where Role_1, Role_2 etc are from the userRole list.
var claim = new[] { new Claim("username", username) new Claim("roles", "Role_1") new Claim("roles", "Role_2") new Claim("roles", "Role_3") new Claim("roles", "Role_4") }
-
How can I add/update a claim in .NET Core 3.1 after I've already authenticated?
In my scenario, I have a many-to-many relationship between users and businesses. So, a business can have many employees, and a user can be an employee to many businesses.
On the login page, I only want to show email & password textboxes. Once they authenticate successfully, I'd like to redirect them to a page that has a dropdown of the businesses they're employed with.
Since they have already authenticated, their claims have already been populated. How do I add another claim (their BusinessID) afterwards?