Am trying to create a user database that I can modify to suit what my users will need to submit when registering for my service, I've created the database and am able to modify it and include whatever columns I want but I can't seem to access them in my c# code, the only fields that appear are those native to AspNetUsers, I've tried looking at similar questions but I can't seem to grasp the concepts specific to what I need, anyone that can help me get some clarity on this cause am a bit new to working with IdentityUser.
//Registration/Login
public class Identify : IIdentify
{
private readonly UserManager<IdentityUser> _manager;
private readonly Mystery _jwtset;
private readonly DataContext _personality;
public Identify(UserManager<IdentityUser> userManager, Mystery jW, DataContext users)
{
_manager = userManager;
_jwtset = jW;
_personality = users;
}
public async Task<Authentication_result> RegisterAsync(string email, string password, string Username)
{
var exists = await _manager.FindByEmailAsync(email);
if (exists != null)
{
return new Authentication_result
{
Errors = new[] { "User with this email already exists" }
};
}
var newPerson = new IdentityUser()
{
Email = email,
UserName = Username
};
var Creation = await _manager.CreateAsync(newPerson, password);
if (!Creation.Succeeded)
{
return new Authentication_result
{
Errors = new[] { "Invalid user!" }
};
}
return Generate_Authentication_Result(newPerson);
}
public async Task<Authentication_result> LoginAsync(string email, string Password)
{
var exists = await _manager.FindByEmailAsync(email);
if (exists == null)
{
return new Authentication_result
{
Errors = new[] { "User does not exists" }
};
}
var pass_validation = await _manager.CheckPasswordAsync(exists, Password);
if (!pass_validation)
{
return new Authentication_result
{
Errors = new[] { "f78wrvep034rf wrong" }
};
}
return Generate_Authentication_Result(exists);
}
private Authentication_result Generate_Authentication_Result(IdentityUser newPerson)
{
var Tokenhandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtset.Secret);
var TokenDescripter = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, newPerson.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, newPerson.Email),
new Claim("id",newPerson.Id)
}),
Expires = DateTime.UtcNow.AddHours(2),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = Tokenhandler.CreateToken(TokenDescripter);
return new Authentication_result
{
Success = true,
Token = Tokenhandler.WriteToken(token)
};
}
}
//Controller for the above
public class IdentifyMe : Controller
{
private readonly IIdentify _identify;
public IdentifyMe(IIdentify identifying)
{
_identify = identifying;
}
[HttpPost(Api_Routes.Identity.Register)]
public async Task<IActionResult> Register(UserRegistration register)
{
if (!ModelState.IsValid)
{
return BadRequest(new Unauthenticated
{
Errors = ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage))
});
}
var authresponce = await _identify.RegisterAsync(register.Email, register.Password, register.User_Name);
if (!authresponce.Success)
{
return BadRequest(new Unauthenticated
{
Errors = authresponce.Errors
});
}
return Ok(new Authenticated
{
Token = authresponce.Token
});
}
[HttpPost(Api_Routes.Identity.Login)]
public async Task<IActionResult> LoginAsync(User_login login)
{
var authresponce = await _identify.LoginAsync(login.email, login.Password);
if (!authresponce.Success)
{
return BadRequest(new Unauthenticated
{
Errors = authresponce.Errors
});
}
return Ok(new Authenticated
{
Token = authresponce.Token
});
}
}
//Domain object, these are the values I would like to be able to access
public class Users : IdentityUser
{
public string PreferredNet { get; set; }
public int Inactive { get; set; }
public int Active { get; set; }
public int Max_Return { get; set; }
public DateTime Time { get; set; }
}
//Other controller
public ActionResult <IEnumerable<Time_dto>> Getitem(string usernum, int amt, string user, string server)
{
var Total = caller.Getusers();
//This is my attempt to acces the domain object, pitcture below[![Intelisense does not display fields in domain object][1]][1]
var container=Total.Select(x=>x.)
var totalin = _digital.Map<IEnumerable<User_dto>>(Total).Count(x => x.PreferredNet == user);
var totalout= _digital.Map<IEnumerable<User_dto>>(Total).Count(x=>x.PreferredNet== server);
int factor = 1;
var HCD = caller.rates(factor, user, server);
var result = shift;
int retrive = caller.Total(amt, user, server, HCD);
var serials = caller.cards(retrive);
int differential = retrive > serials.Sum() ? retrive serials.Sum() : serials.Sum() - retrive;
int number = serials.Count();
IEnumerable<int> Real_cards=new List<int>();
}
```
[1]: https://i.stack.imgur.com/HEenG.png
Related
In my ASP.NET Core-6 Web API, I have an external API to consume. I am to validate the account using a parameter, register the user if not in existence, then Login with the same detail.
API:
https://api.thirdpartycompany.com/UserAccount/api/CustomerDetail?userName=
First, it checks if the customer exists in the external API using userName as parameter.
public class GetCustomerDetailDto
{
public class CustomerDetail
{
public string FirstName { get; set; }
public object LastName { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
}
}
I validated the third party API using this method:
interface:
public interface IDataUtil
{
CustomerDetail GetCustomerDetail(string userName);
}
Implementation:
public class DataUtil : IDataUtil
{
private readonly IConfiguration _config;
private readonly ILogger<DataUtil> _logger;
private readonly HttpClient _myClient;
public DataUtil
(
IConfiguration config,
ILogger<DataUtil> logger,
HttpClient myClient
)
{
_config = config;
_logger = logger;
_myClient = myClient;
}
public CustomerDetail GetCustomerDetail(string userName)
{
var responseResults = new CustomerDetail();
_logger.LogError($"responseResults: " + responseResults);
try
{
string custAccountNoUrl = _config.GetSection("Endpoints").GetValue<string>("custAccountDetailUrl") + userName;
_myClient.DefaultRequestHeaders.Accept.Clear();
_myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = _myClient.GetAsync(custAccountNoUrl).Result;
if (response.IsSuccessStatusCode)
{
var stringResult = response.Content.ReadAsStringAsync().Result;
responseResults = JsonConvert.DeserializeObject<CustomerDetail>(stringResult);
}
}
catch (Exception ex)
{
_logger.LogError($"An Error occured " + ex.ToString());
}
return responseResults;
}
}
I have these Auth DTOs:
public class UserDto
{
public string Id { get; set; }
public string FirstName { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public DateTime LastLogin { get; set; }
}
public class LoginRequestDto
{
[Required(ErrorMessage = "The username is required!")]
public string UserName { get; set; }
[Required(ErrorMessage = "The password is required!")]
public string Password { get; set; }
}
public class LoginResponseDto
{
public string JwtToken { get; set; }
public UserDto User { get; set; }
public DateTime Expires { get; set; }
}
public class RegistrationRequestDto
{
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Model:
public class AppUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime LastLogin { get; set; }
}
And now the AuthService.
IAuthService:
public interface IAuthService
{
Task<GenericResponseDto<object>> LoginUser(LoginRequestDto request);
Task<GenericResponseDto<UserDto>> CreateUserAsync(RegistrationRequestDto requestDto);
}
AuthService:
private async Task<GenericResponseDto<UserDto>> CreateUserAsync(RegistrationRequestDto requestDto)
{
var response = new GenericResponseDto<UserDto>();
var existingUser = await _userManager.FindByNameAsync(requestDto.UserName);
if (existingUser == null)
{
var userDetail = _dataUtil.GetCustomerDetail(requestDto.UserName);
var user = new AppUser()
{
UserName = userDetail.UserName.ToLower().Trim(),
Email = userDetail.EmailAddress.Trim().ToLower(),
FirstName = userDetail.FirstName.Trim(),
LastName = userDetail.LastName.Trim(),
CreatedAt = DateTime.Now
};
user.SecurityStamp = Guid.NewGuid().ToString();
var result = await _userManager.CreateAsync(user, "Adminpass1");
if (!result.Succeeded)
{
var error = string.Join<IdentityError>(", ", result.Errors.ToArray());
response.Error = new ErrorResponseDto { ErrorCode = 500, Message = "Failed to create user because of the following errors: " + error };
}
else
{
response.StatusCode = 200;
response.Result = _mapper.Map<UserDto>(user);
}
} else
{
response.Error = new ErrorResponseDto { ErrorCode = 400, Message = "This email is already registered!" };
response.StatusCode = 400;
}
return response;
}
public async Task<GenericResponseDto<object>> LoginUser(LoginRequestDto request)
{
var user = await _userManager.FindByNameAsync(request.UserName);
var response = new GenericResponseDto<object>();
if (user != null && await _userManager.CheckPasswordAsync(user, request.Password))
{
var roles = await _userManager.GetRolesAsync(user);
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
foreach (var userRole in roles)
{
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
}
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
var token = new JwtSecurityToken(
issuer: _configuration["JWT:ValidIssuer"],
audience: _configuration["JWT:ValidAudience"],
expires: DateTime.Now.AddHours(3),
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
response.Result = new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
user = _mapper.Map<UserDto>(user),
expires = token.ValidTo
};
response.StatusCode = 200;
user.LastLogin = DateTime.Now;
try
{
await _context.SaveChangesAsync();
}catch(Exception ex)
{
response.Error = new ErrorResponseDto() { ErrorCode = 500, Message = ex.Message };
}
return response;
}
response.StatusCode = 400;
response.Error = new ErrorResponseDto { ErrorCode = 400, Message = "Invalid email or password!" };
return response;
}
In the application, users are not allowed to register manually.
So far, I have created the LoginUser and CreateUserAsync methods.
What I want to achieve is that, when the user tries to login the application checks if username already exists. If yes, it logs in, if no it checks from the external API using UserName as parameter, gets the user data, register the user using CreateUserAsync. Then automatically re-login the user.
How do I achieve this?
NOTE: I am using IdentityDB and EntityFramework
Thanks
Till .net5 I've been Seeding data using the following in startup.cs file:
SeedData.Seed(_userManager, _roleManager);
And then in a seperate file SeedData.cs, the following code:
public static class SeedData
{
public static void Seed(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
{
SeedRoles(roleManager);
SeedUsers(userManager);
}
private static void SeedUsers(UserManager<IdentityUser> userManager)
{
if(userManager.FindByNameAsync("admin#localhost.com").Result == null)
{
var user = new IdentityUser
{
UserName = "admin#localhost.com",
Email = "admin#localhost.com"
};
var result = userManager.CreateAsync(user, "P#ssword1").Result;
if(result.Succeeded)
{
userManager.AddToRoleAsync(user, "Administrator").Wait();
}
}
}
private static void SeedRoles(RoleManager<IdentityRole> roleManager)
{
if(!roleManager.RoleExistsAsync("Administrator").Result)
{
var role = new IdentityRole
{
Name = "Administrator",
};
var result = roleManager.CreateAsync(role).Result;
}
if(!roleManager.RoleExistsAsync("Employee").Result)
{
var role = new IdentityRole
{
Name = "Employee",
};
var result = roleManager.CreateAsync(role).Result;
}
}
}
Now, how do i do the same with .net6, since it has only program.cs file?
This is what I personally do:
I make an extension to IApplicationBuilder:
public static class ApplicationBuilderExtensions
{
public static async Task<IApplicationBuilder> PrepareDatabase(this IApplicationBuilder app)
{
using var scopedServices = app.ApplicationServices.CreateScope();
var serviceProvider = scopedServices.ServiceProvider;
var data = serviceProvider.GetRequiredService<NeonatologyDbContext>();
data.Database.Migrate();
await SeedAdministratorAsync(serviceProvider);
await SeedDoctorAsync(data, serviceProvider);
return app;
}
Here are the seedings:
private static async Task SeedDoctorAsync(NeonatologyDbContext data, IServiceProvider serviceProvider)
{
if (data.Doctors.Any())
{
return;
}
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = serviceProvider.GetRequiredService<RoleManager<ApplicationRole>>();
var identityRole = new ApplicationRole()
{
Name = DoctorRoleName
};
await roleManager.CreateAsync(identityRole);
var city = await data.Cities.Where(x => x.Name == "Плевен").FirstOrDefaultAsync();
var doctor = new ApplicationUser()
{
Email = DoctorEmail,
UserName = DoctorEmail,
EmailConfirmed = true,
Doctor = new Doctor
{
FirstName = DoctorFirstName,
LastName = DoctorLastName,
PhoneNumber = DoctorPhone,
Address = Address,
Age = DoctorAge,
Biography = Biography,
CityId = city.Id,
City = city,
YearsOfExperience = YearsOfExperience,
Email = DoctorEmail
}
};
await userManager.CreateAsync(doctor, DoctorPassword);
await userManager.AddToRoleAsync(doctor, identityRole.Name);
doctor.Doctor.UserId = doctor.Id;
doctor.Doctor.Image = new Image()
{
RemoteImageUrl = "SomeURL"
};
await data.SaveChangesAsync();
}
private static async Task SeedAdministratorAsync(IServiceProvider serviceProvider)
{
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = serviceProvider.GetRequiredService<RoleManager<ApplicationRole>>();
if (await roleManager.RoleExistsAsync(AdministratorRoleName))
{
return;
}
var identityRole = new ApplicationRole()
{
Name = AdministratorRoleName
};
await roleManager.CreateAsync(identityRole);
const string adminEmail = AdministratorEmail;
const string adminPassword = AdministratorPassword;
var adminUser = new ApplicationUser()
{
Email = adminEmail,
UserName = adminEmail,
EmailConfirmed = true
};
if (await userManager.IsInRoleAsync(adminUser, identityRole.Name))
{
return;
}
await userManager.CreateAsync(adminUser, adminPassword);
await userManager.AddToRoleAsync(adminUser, identityRole.Name);
}
And in the Program.cs I have:
app.PrepareDatabase()
.GetAwaiter()
.GetResult();
The following snippet works for me and seeds the data upon initialization of the application.
Hello I have a 'RestrictAccessController' That looks like this
public class RestrictAccessController : Controller
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public ActionResult Index()
{
return View ();
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=true)]
public class RestrictAccessAttribute : ActionFilterAttribute
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public AccessRestrictions restriction { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// here's where we check that the current action is allowed by the current user
if (!IGT.canAccess(IGT.userId, restriction, false))
{
string url = IGT.baseUrl+"/Home/NotAllowed";
string msg = "This page requires " + IGT.DisplayEnum(restriction) + " access";
filterContext.Result = new RedirectResult("~/Home/NotAllowed?msg="+HttpUtility.HtmlEncode(msg));
}
}
And a Config model that looks like this
public enum AccessRestrictions
{
[Display(Name = "Disposal Orders")]
ModifyDisposalOrder,
[Display(Name = "Admin")]
Admin
}
public class userAccess
{
[Key]
public int ID { get; set; }
public AccessRestrictions restriction { get; set; }
public bool allow { get; set; }
public int userID { get; set; }
}
public class configDetails
{
public int ID {get; set;}
public string Name {get; set;}
public string Value {get;set;}
public bool deleted {get;set;}
public DateTime updateTime { get; set; }
}
public class Config
{
public int ID { get; set; }
[Display(Name = "Configuration Date")]
public DateTime TargetDate { get; set; }
[Display(Name = "Enable Access Restrictions")]
public bool restrictAccess { get; set; }
}
What I want to do is edit what my 'ChangeStatus' dropdown looks like based on whether they have the Admin access restriction or not. Here is the controller method that I want to edit
[RestrictAccess(restriction = AccessRestrictions.ModifyDisposalOrder)]
public ActionResult ChangeStatus(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DisposalOrder disposalOrder = db.disposalOrders.Find(id);
if (disposalOrder == null)
{
return HttpNotFound();
}
switch (disposalOrder.Status)
{
case DOStatus.Pending:
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
break;
case DOStatus.Disposed:
// if(restriction = AccessRestrictions.ModifyDisposalOrder)
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
//else
//{
// new { value = DOStatus.Disposed, text = "Disposed" }
// };
break;
};
return View(disposalOrder);
}
Here is my Startup file
public class LdapAuthentication
{
private string _adUser = ConfigurationManager.AppSettings["ADUserName"];
private string _adPW = ConfigurationManager.AppSettings["ADPassword"];
private string _domain = ConfigurationManager.AppSettings["ADDomain"];
public LdapAuthentication() {
}
public string authenticate(string username, string pwd)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW)) {
//Username and password for authentication.
if (context.ValidateCredentials(username, pwd)) {
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
Internal internalUser = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
//Search if the user account already exists in the database
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
Internal existing = db.Internals.Where(x => x.UserName == user.SamAccountName).FirstOrDefault();
// If it does not, create a new user account
if (existing == null) {
// add a new Internal entry for this user
existing = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
db.Internals.Add(existing);
db.SaveChanges();
// If it does exist, but some of the data does not match, update the data
} else if(existing != internalUser) {
existing.ContactName = internalUser.ContactName;
existing.Email = internalUser.Email;
db.SaveChanges();
}
return user.SamAccountName;
} else {
return null;
}
}
}
public UserPrincipal getUserPrincipal(string username)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW))
{
return UserPrincipal.FindByIdentity(context, username);
}
}
Is it possible for me to accomplish this?
Ok, I think I understand your question now. You need to access the User's claims. MVC Controllers have this, half way, built in.
if (User.HasClaim("ClaimNameHere", "Admin"))
{
}
Solved by adding
if (IGT.canAccess(IGT.userId, AccessRestrictions.Admin, false))
I am trying to update employee record and want to update identity user too.
If i update Identity User first separately
For Example:
UserManager.Update(user);
Context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
Context.SaveChanges();
and then update the employee.
maybe it is possible identity user updates with success but employee update process gets an error.
so IdentityUser is updated now but the employee is not.
how to handle this situation.
please guide.
public class Employee
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string AppUserId { get; set; }
[ForeignKey("AppUserId")]
public virtual AppUser AppUser { get; set; }
}
public class AppUser : IdentityUser<string, AppUserLogin, AppUserRole, AppUserClaim>, IUser<string>
{
public AppUser()
{
this.Id = Guid.NewGuid().ToString();
}
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<AppUser, string> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsActive { get; set; }
}
public JsonResult Create(EmployeeVM evm, AppUserVM appUser)
{
var jsonResult = new JsonResult();
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
if (ModelState.IsValid)
{
var user = new AppUser();
evm.CreatedDate = DateTime.Now.Date;
appUser.PasswordHash = "dummypass";
user = Mapper.Map<AppUser>(appUser);
var employee = Mapper.Map<Employee>(evm);
employee.AppUser = user;
try
{
if (userService.CreateEmployee(employee))
{
jsonResult.Data = new { Success = true, message = "Success Added Record"};
}
}
catch (Exception ex)
{
jsonResult.Data = new { Success = false, message =ex.Message};
}
}
else
{
jsonResult.Data = new { Success = false, message = ModelErrors() };
}
return jsonResult;
}
public bool CreateEmployee(Employee employee)
{
Context.Employees.Add(employee);
return Context.SaveChanges()>0;
}
Adding new record works fine.
but when i update the record. i don't know how to update both records at once.
For Example:
public JsonResult Edit(EmployeeVM evm, AppUserVM appUserVM)
{
ModelState.Remove(nameof(evm.CreatedDate));
var jsonResult = new JsonResult();
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
if (ModelState.IsValid)
{
appUserVM.UserName = appUserVM.Email;
var user = UserManager.FindById(evm.UserId);
user.Email = appUserVM.Email;
user.UserName = appUserVM.UserName;
user.FirstName = appUserVM.FirstName;
user.LastName = appUserVM.LastName;
user.IsActive = appUserVM.IsActive;
user.PhoneNumber = appUserVM.PhoneNumber;
var employee = Mapper.Map<Employee>(evm);
employee.AppUser = user;
employee.Id = evm.Id;
employee.AppUserId = user.Id;
try
{
if(userService.UpdateEmployee(employee))
jsonResult.Data = new { Success = true, message = "Success" };
}
catch (Exception ex)
{
jsonResult.Data = new { Success = false, message = ex.Message };
}
}
else
{
jsonResult.Data = new { Success = false, message = ModelErrors() };
}
return jsonResult;
}
public bool UpdateEmployee(Employee employee)
{
Context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
return Context.SaveChanges() > 0;
}
Without seeing the exception, I'm not sure what the issue is, but you could trying using an attached entity and set values like the following.
var dbEmployee = Context.Emplyoees.SingleOrDefault(s => s.Id == employee.Id);
if (dbEmployee!= null)
Context.Entry(dbEmployee).CurrentValues.SetValues(employee);
The User employee service should be
public bool UpdateEmployee(Employee employee)
{
var existingEmployee = Context.Emplyoees.FirstOrDefault(s => s.Id == employee.Id);
if (existingEmployee != null)
{
//do the update to the database
Context.Entry(existingEmployee).CurrentValues.SetValues(employee);
Context.Entry(existingEmployee).State = System.Data.Entity.EntityState.Modified;
return Context.SaveChanges() > 0;
}
else return false;
}
I'm getting this error even though I only have one GET on the page. So I'm thoroughly confused.
Here's what the whole login page looks like:
public class LoginModel : PageModel
{
private UserAuthenticationService _userAuthenticationService { get; set; }
private ClaimService _claimService { get; set; }
public LoginModel(UserAuthenticationService userAuthenticationService, ClaimService claimService)
{
_userAuthenticationService = userAuthenticationService;
_claimService = claimService;
}
public async Task OnGetAsync()
{
var user = _userAuthenticationService.Login();
if (user == null)
{
//TODO: Login failed
}
else
{
var claims = _claimService.GetClaimsFromUserModel(user);
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties()
{
ExpiresUtc = DateTime.UtcNow.AddDays(6),
IsPersistent = true,
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties);
}
}
And here's the error. I only have one OnGet, so I don't know why it's saying there are multiple. Any ideas?