Use Identity to create and verify token secret hash.

This commit is contained in:
Jared Goodwin 2020-02-24 13:16:42 -08:00
parent e43ca309e8
commit d2df890225
2 changed files with 11 additions and 5 deletions

View File

@ -4,8 +4,10 @@ using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Remotely.Server.Auth;
using Remotely.Server.Services;
using Remotely.Shared.Models;
@ -58,9 +60,12 @@ namespace Remotely.Server.Areas.Identity.Pages.Account.Manage
{
if (ModelState.IsValid && !string.IsNullOrWhiteSpace(Input.TokenName))
{
var newToken = await DataService.CreateApiToken(User.Identity.Name, Input.TokenName);
var secret = PasswordGenerator.GeneratePassword(24);
var secretHash = new PasswordHasher<RemotelyUser>().HashPassword(null, secret);
var newToken = await DataService.CreateApiToken(User.Identity.Name, Input.TokenName, secretHash);
NewTokenKey = Guid.Parse(newToken.Token);
NewTokenSecret = newToken.Secret;
NewTokenSecret = secret;
Message = "New token created.";
}
PopulateViewModel();

View File

@ -223,7 +223,7 @@ namespace Remotely.Server.Services
}
}
public async Task<ApiToken> CreateApiToken(string userName, string tokenName)
public async Task<ApiToken> CreateApiToken(string userName, string tokenName, string secretHash)
{
var user = RemotelyContext.Users.FirstOrDefault(x => x.UserName == userName);
@ -232,7 +232,7 @@ namespace Remotely.Server.Services
Name = tokenName,
OrganizationID = user.OrganizationID,
Token = Guid.NewGuid().ToString(),
Secret = PasswordGenerator.GeneratePassword(24)
Secret = secretHash
};
RemotelyContext.ApiTokens.Add(newToken);
await RemotelyContext.SaveChangesAsync();
@ -643,8 +643,9 @@ namespace Remotely.Server.Services
public bool ValidateApiToken(string apiToken, string apiSecret, string requestPath, string remoteIP)
{
var hasher = new PasswordHasher<RemotelyUser>();
var token = RemotelyContext.ApiTokens.FirstOrDefault(x => x.Token == apiToken);
var isValid = token != null && token.Secret == apiSecret;
var isValid = token != null && hasher.VerifyHashedPassword(null, token.Secret, apiSecret) == PasswordVerificationResult.Success;
if (token != null)
{