How to retrieve Claims Value in .Net Core 2.0 - asp.net-core-2.0

As it says in the title I have already assigned claims to the registered user, I am now trying to retrieve the claim value when the user logs into the application within the UserClaims table in sql server which I find a bit difficult to do as this is my first time using claims.
Looking for directions on our to achieve this, thank you in advance.
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, UserRoleId = model.RoleId };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created a new account with password.");
await addUserClaims(model.CusomterId, model.UserName);
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
List<UserRole> roles = _userRoleRepo.GetAll();
model.CreateRoleList(roles);
List<Customer> customers = await _customerRepository.GetAll();
model.SetupCustomerOptionList(customers);
// If we got this far, something failed, redisplay form
return View(model);
}
private async Task addUserClaims(string CustomerID ,string username)
{
// Customer customer = _customerRepository.GetById(customerid);
List<Customer> customers = await _customerRepository.GetAll();
Customer customer = _customerRepository.GetById(CustomerID);
var user = await _userManager.FindByNameAsync(username);
;
await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Name, CustomerID));
}

Set
var claims = new List<Claim>
{
new Claim("Currency", "PKR")
};
Get
#User.Claims.FirstOrDefault(c => c.Type == "Currency").Value

Very easy
public static class IdentityExtension
{
public static string GetId(this IIdentity identity)
{
ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
Claim claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
return claim.Value;
}
}
Example
User.Identity.GetId();

Related

Azure Table Storage not saving all object properties

I have a problem with the Azure Table Storage. What I'm trying to achieve is saving the ChangeToken of the SharePoint list in order to use the webhooks properly.
Here is the code:
public class TablesHelper
{
private static readonly string TokenTableName = "TokenTable";
public static async Task<ListChangeToken> GetChangeTokenForListAsync(string listId)
{
var retrieveOperation = TableOperation.Retrieve<ListChangeToken>("Lists", listId, new List<string>() { "ChangeToken" });
var tableReference = await GetTableReferenceAsync(TokenTableName);
var tableResult = await tableReference.ExecuteAsync(retrieveOperation);
if(tableResult.Result != null)
{
return tableResult.Result as ListChangeToken;
}
return null;
}
public static async Task SaveChangeTokenForListAsync(ListChangeToken changeToken)
{
var insertOperation = TableOperation.Insert(changeToken);
var tableReference = await GetTableReferenceAsync(TokenTableName);
var result = await tableReference.ExecuteAsync(insertOperation);
}
private static async Task<CloudTable> GetTableReferenceAsync(string tableName)
{
var storageAccount = CloudStorageAccount.Parse(ConfigurationHelper.CloudStorage);
var tableClient = storageAccount.CreateCloudTableClient();
var reference = tableClient.GetTableReference(tableName);
await reference.CreateIfNotExistsAsync();
return reference;
}
}
The ListChangeToken class:
public class ListChangeToken : TableEntity
{
public ListChangeToken(string listId, string changeToken)
{
this.PartitionKey = "Lists";
this.RowKey = listId;
this.ChangeToken = changeToken;
}
public ListChangeToken() { }
public string ChangeToken { get; set;}
}
As per request, the function calling TablesHelper:
[FunctionName("EventHandler")]
public static async Task Run([QueueTrigger("events", Connection = "CloudStorage")]string myQueueItem, TraceWriter log)
{
var notificationGroup = Newtonsoft.Json.JsonConvert.DeserializeObject<NotificationGroup>(myQueueItem);
var contextHelper = new ContextHelper();
foreach (var notification in notificationGroup.Value)
{
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = "https";
uriBuilder.Host = ConfigurationHelper.TenantDomain;
uriBuilder.Path = notification.SiteUrl;
using (var ctx = contextHelper.GetAppOnlyContext(uriBuilder.ToString()))
{
//Read change token
var currentChangeToken = await TablesHelper.GetChangeTokenForListAsync(notification.Resource);
if(currentChangeToken == null)
{
log.Error($"No change token found for list {notification.Resource}. This is a NO GO. Please use the '/api/Setup' function.");
}
var listId = Guid.Parse(notification.Resource);
var changes = await CSOMHelper.GetListItemChangesAsync(ctx, listId, currentChangeToken.ChangeToken);
if(changes.Count > 0)
{
var lastChange = changes[changes.Count - 1];
//Save the last change token
var changeTokenValue = lastChange.ChangeToken.StringValue;
await TablesHelper.SaveChangeTokenForListAsync(new ListChangeToken(
notification.Resource,
changeTokenValue
));
await HandleChanges(ctx, changes);
}
}
}
log.Info($"C# Queue trigger function processed: {myQueueItem}");
}
The problem is that always, when using the "GetChangeTokenForListAsync" the Entity is received properly, but the .ChangeToken property is always null. It is also not visible when browsing with the Azure Storage Explorer. What am I doing wrong here?
The issue is related to the Azure Storage Emulator (V. 5.7.0.0). The same code works perfectly when working with the "live" Azure.

Active Directory authentication for Umbraco 7.6 gets stuck in a re-direct loop

I am currently using an Umbraco library to extend the Authentication possibilities and enable back office authentication with Active Directory.
https://github.com/umbraco/UmbracoIdentityExtensions
After installing the library and following the blog post below, I was able to display an external login button, authenticate with Active Directory and add a user and external login to the Umbraco database.
https://www.jdibble.co.uk/blog/securing-umbraco-backoffice-with-azure-active-directory/
This then sends you back to the /umbraco login page in a continuous loop. As described by this blog post https://our.umbraco.org/forum/developers/extending-umbraco/75256-login-uisng-azure-ad-redirects-allways-to-login-page
Has anyone faced this issue and solved it? Or have any useful suggestions?
The code being used...
public static void ConfigureBackOfficeAzureActiveDirectoryAuth(this IAppBuilder app,
string tenant, string clientId, string postLoginRedirectUri, Guid issuerId,
string caption = "Active Directory", string style = "btn-microsoft", string icon = "fa-windows")
{
var authority = string.Format(
CultureInfo.InvariantCulture,
"https://login.microsoftonline.com/{0}",
tenant);
var adOptions = new OpenIdConnectAuthenticationOptions
{
SignInAsAuthenticationType = Constants.Security.BackOfficeExternalAuthenticationType,
ClientId = clientId,
Authority = authority,
RedirectUri = postLoginRedirectUri,
AuthenticationMode = AuthenticationMode.Passive,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async context =>
{
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
var userService = ApplicationContext.Current.Services.UserService;
var stuff = (List<Claim>)context.JwtSecurityToken.Claims;
var email = stuff.FirstOrDefault(x => x.Type == "unique_name").Value;
var issuer = stuff.FirstOrDefault(x => x.Type == "iss").Value;
var providerKey = stuff.FirstOrDefault(x => x.Type == "sub").Value;
var name = stuff.FirstOrDefault(x => x.Type == "name").Value;
var userManager = context.OwinContext.GetUserManager<BackOfficeUserManager>();
var user = userService.GetByEmail(email);
if (user == null)
{
var writerUserType = userService.GetUserTypeByName("writer");
user = userService.CreateUserWithIdentity(email, email, writerUserType);
}
var identity = await userManager.FindByEmailAsync(email);
if (identity.Logins.All(x => x.ProviderKey != providerKey))
{
identity.Logins.Add(new IdentityUserLogin(issuer, providerKey, user.Id));
identity.Name = name;
var result = userManager.Update(identity);
}
},
}
};
adOptions.ForUmbracoBackOffice(style, icon);
adOptions.Caption = caption;
//Need to set the auth type as the issuer path
adOptions.AuthenticationType = string.Format(
CultureInfo.InvariantCulture,
"https://sts.windows.net/{0}/",
issuerId);
adOptions.SetExternalSignInAutoLinkOptions(new ExternalSignInAutoLinkOptions(autoLinkExternalAccount: true));
app.UseOpenIdConnectAuthentication(adOptions);
}

Manually hashing password the same as ASP.NET Identity v2.2.1

I have an ASP.NET Web Api that makes use of ASP.NET Identity v2.2.1 to manage users. I am able to add/edit users without issue. However, I have a second project that cannot make use of the API but needs to be able to change a Users password directly via the database.
I am trying to figure out how to hash the password entered by the user without going through the API. I need to make sure that I am using the same hashing algorithm that ASP.NET Identity is using. I came across some code in this SO article but I am not sure if it is the same hashing algorithm used by v2.2.1.
using using System.Security.Cryptography;
public static string HashPassword(string password)
{
private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
private const int SaltSize = 128 / 8; // 128 bits
if (password == null)
{
throw new ArgumentNullException("password");
}
// Produce a version 0 (see comment above) text hash.
byte[] salt;
byte[] subkey;
using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount))
{
salt = deriveBytes.Salt;
subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
}
var outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength];
Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize);
Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength);
return Convert.ToBase64String(outputBytes);
}
I would like to avoid having to add ASP.NET Identity as a dependency to this project hence why I would like to hash the password manually.
I would recommend you to use SimpleCrypto
This is how I've used that in a project I believe this will help you. One can add this DLL from nuget
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
try
{
if (ModelState.IsValid)
{
{
var crypto = new SimpleCrypto.PBKDF2();
var encrypPass = crypto.Compute(model.Password);
var newUser = db.Users.Create();
newUser.Email = model.Email;
newUser.Password = encrypPass;
newUser.PasswordSalt = crypto.Salt;
// newUser.Name = model.UserName;
newUser.Username = model.UserName;
//newUser.AddedBy = model.;
db.Users.Add(newUser);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "");
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return View();
}
Your valid check at login will be like this
private bool IsValid(string email, string password)
{
var crypto = new SimpleCrypto.PBKDF2();
bool isValid = false;
{
var user = db.Users.FirstOrDefault(u => u.Email == email);
if (user != null)
{
if (user.Password == crypto.Compute(password, user.PasswordSalt))
{
isValid = true;
}
}
}
return isValid;
}

Send email using Office 365 using unified API

We are trying to use the O365 Unified API to send emails from our line-of-business apps. I use the following code to send the email. This throws a DataServiceQueryException exception "Unauthorized".
public async Task SendEmailAsUserAsync(EmailMessage message)
{
try
{
var graphClient = await _authenticationHelper.GetGraphClientAsync();
Message m = InitializeMessage(message);
await graphClient.Me.SendMailAsync(m, true);
}
catch (DataServiceQueryException dsqe)
{
_logger.Error("Could not get files: " + dsqe.InnerException.Message, dsqe);
throw;
}
}
private static Message InitializeMessage(EmailMessage message)
{
ItemBody body = new ItemBody {Content = message.Body, ContentType = BodyType.HTML};
Message m = new Message
{
Body = body,
Subject = message.Subject,
Importance = Importance.Normal,
};
//Add all the to email ids
if (message.ToRecipients != null)
foreach (Models.Messaging.EmailAddress emailAddress in message.ToRecipients)
{
m.ToRecipients.Add(new Recipient { EmailAddress = new Microsoft.Graph.EmailAddress { Address = emailAddress.Address, Name = emailAddress.Name } });
}
return m;
}
The code for _authenticationHelper.GetGraphClientAsync() is
public async Task<GraphService> GetGraphClientAsync()
{
Uri serviceRoot = new Uri(appConfig.GraphResourceUriBeta + appConfig.Tenant);
_graphClient = new GraphService(serviceRoot,
async () => await AcquireTokenAsyncForUser(appConfig.GraphResourceUri, appConfig.Tenant));
return _graphClient;
}
private async Task<string> AcquireTokenAsyncForUser(string resource, string tenantId)
{
AuthenticationResult authenticationResult = await GetAccessToken(resource, tenantId);
_accessCode = authenticationResult.AccessToken;
return _accessCode;
}
private async Task<AuthenticationResult> GetAccessToken(string resource, string tenantId)
{
string authority = appConfig.Authority;
AuthenticationContext authenticationContext = new AuthenticationContext(authority);
ClientCredential credential = new ClientCredential(appConfig.ClientId, appConfig.ClientSecret);
string authHeader = HttpContext.Current.Request.Headers["Authorization"];
string userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim();
UserAssertion userAssertion = new UserAssertion(userAccessToken);
var authenticationResult = await authenticationContext.AcquireTokenAsync(resource, credential, userAssertion);
return authenticationResult;
}
However if I change the SendEmailAsUserAsync method as shown below, the email is sent but an InvalidOperationException is thrown with message "The complex type 'System.Object' has no settable properties."
public async Task SendEmailAsUserAsync(EmailMessage message)
{
try
{
var graphClient = await _authenticationHelper.GetGraphClientAsync();
Message m = InitializeMessage(message);
//await graphClient.Me.SendMailAsync(m, true); //This did not work
var user = await graphClient.Me.ExecuteAsync();
await user.SendMailAsync(m, true);
}
catch (DataServiceQueryException dsqe)
{
_logger.Error("Could not get files: " + dsqe.InnerException.Message, dsqe);
throw;
}
}
Can any one point out if there is something wrong here.
Check the example project below, this has a working example (after you fill in the ClientID etc. in app.config).
Office 365 API demo applications
For sending email it uses the function below, which works if you set it up correctly. It also has a number of functions for Authenticating using Authorization Code Grant Flow.
public async Task SendMail(string to, string subject, string body)
{
var client = await this.AuthenticationHelper
.EnsureOutlookServicesClientCreatedAsync(
Office365Capabilities.Mail.ToString());
Message mail = new Message();
mail.ToRecipients.Add(new Recipient()
{
EmailAddress = new EmailAddress
{
Address = to,
}
});
mail.Subject = subject;
mail.Body = new ItemBody() { Content = body, ContentType = BodyType.HTML };
await client.Me.SendMailAsync(mail, true);
}
Actually, there is no assembly wrapper for the graph API.
Microsoft.Graph.dll is deprecrated.
So, you should to :
Deal with the REST requests : See here : http://graph.microsoft.io/docs/api-reference/v1.0/api/message_send
Generate a wrapper with Microsoft.Vipr project : see here : https://github.com/microsoft/vipr
For the authentication, ADAL works fine :)

Orchard CMS Duplicate entry when creating a user

I have been breaking my head over this. Please take a look at this code. This code is in the customer controller.
[HttpPost]
[Themed]
public ActionResult Register(string email, string password, string confirmPassword, Gender gender, string givenName, string familyName, string insertion, DateTime birthDate) {
ViewData["PasswordLength"] = MinPasswordLength;
var shape = _orchardServices.New.Register();
//1. Initialize new content of customer contenttype
var customer = _orchardServices.ContentManager.New("Customer");
if (customer != null) {
//2. Define the parts that need to be filled
var userPart = customer.As<UserPart>();
var customerPart = customer.As<CustomerPart>();
//3. Let's validate first if the user can be created
if (userPart!=null) {
//shape.Customer = _orchardServices.ContentManager.UpdateEditor(customer, this);
if (!ModelState.IsValid)
{
_orchardServices.TransactionManager.Cancel();
return new ShapeResult(this, shape);
}
//4. Now validate the user credentials.
if (ValidateRegistration(email, password, confirmPassword)) {
//Now create the actual customer.
userPart.UserName = email;
userPart.Email = email;
userPart.NormalizedUserName = email.ToLowerInvariant();
userPart.Record.HashAlgorithm = "SHA1";
userPart.Record.RegistrationStatus = UserStatus.Approved;
userPart.Record.EmailStatus = UserStatus.Approved;
customerPart.CreatedAt = DateTime.UtcNow;
customerPart.LastLogonAt = DateTime.UtcNow;
_membershipService.SetPassword(userPart, password);
var user = customerPart.User;
_authenticationService.SignIn(user, false /* createPersistentCookie */);
return Redirect("~/");
}
}
}
When this code is run, I end up with two entries for UserPart in my database. One with a related CustomerPart and one not.

Resources