Click here to Skip to main content
15,355,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am creating an application that should contain a Register form and a Login form in Blazor (C #) Server-Side. I managed to make the Register form successfully, but I can't connect the Login form to the Register form.

Register.razor:

Razor
@page "/register"

@using TestBlazor.Models
@using TestBlazor.Data
@using Microsoft.Data.SqlClient


<br />
<br />

<h3 class="h3">Register</h3>
<br />

<EditForm class="needs-validation" Model="@_user" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit">
    <div class="alert @StatusClass">@StatusMessage</div>
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div class="form-group">
        <p>User name</p>
        <input id="username" class="solid" name="username" placeholder="Your username.." @bind-value="_user.UserName" />
        <ValidationMessage For="@(() => @_user.UserName)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p>Password</p>
        <input type="password" class="solid" id="password" placeholder="Your password.." @bind-value="_user.Password" />
        <ValidationMessage For="@(() => @_user.Password)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p>Email</p>
        <input id="email" class="solid" placeholder="you@example.com" @bind-value="_user.Email" />
        <ValidationMessage For="@(() => @_user.Email)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p>Company</p>
        <input id="company" class="solid" placeholder="Your company.." @bind-value="_user.Company" />
        <ValidationMessage For="@(() => @_user.Company)"></ValidationMessage>
    </div>


    <br />

    <button disabled="@loading" class="btn btn-primary" onclick="AddUser">

        @if (loading)
        {
            
            <NavLink href="/login" class="btn btn-link">Register</NavLink>
        }
        Register
    </button>
    <NavLink href="/login" class="btn btn-link">Login</NavLink>
</EditForm>




C#
@code {
    private User _user = new User();


    private string StatusMessage;
    private string StatusClass;

    private bool loading;


    private void OnValidSubmit()
    {
        if (loading == true)
        {
            Console.WriteLine("You have successfully registered!");
        }

        else
        {
            loading = false;
            Console.WriteLine("Check your information again!");
        }
    }

    //protected void HandleValidSubmit()
    //{
    //    StatusClass = "alert-info";
    //    StatusMessage = " You have successfully registered! Please click the Login button to log in!";

    @*}*@


private async void HandleValidSubmit()
{
    try
    {
        var _dataContext = new AppDbContext();
        _dataContext.User.Add(_user);

        await _dataContext.SaveChangesAsync();
    }
    catch
    {
        base.StateHasChanged();
    }
    _user = new User();
    //obavještava komponentu da se njezino stanje promijenilo
    base.StateHasChanged();
}


protected void HandleInvalidSubmit()
{
    StatusClass = "alert-danger";
    StatusMessage = " Check your information again!";
}


//public bool doesCompanyExist(string Company)
//{
//    using (var domainContext = new AppDbContext(ContextType.Domain, "spl"))
//    {
//        using (var foundUser = AppDbContext.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
//        {
//            if (foundUser != null)
//                return foundUser.Name;
//            else
//                return "User Does not exist ";
//        }
//    }
//}

private Boolean exists(string company)
{
    SqlConnection conn = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=testblazor;Integrated Security=True;");
    SqlCommand cmd = new SqlCommand("Select Count(*)  from Users where Company ='" + company + "'", conn);
    SqlDataReader sReader = null;
    Int32 numberOfRows = 0;

    try
    {
        conn.Open();
        sReader = cmd.ExecuteReader();

        while (sReader.Read())
        {
            if (!(sReader.IsDBNull(0)))
            {
                numberOfRows = Convert.ToInt32(sReader[0]);
                if (numberOfRows > 0)
                {
                    return true;
                }
            }
        }
    }
    catch (Exception ex)
    {

        throw ex;
    }
    finally
    {
        conn.Close();
    }
    return false;
}


//protected void Button1_Click(object sender, EventArgs e)
//{
//    if (!string.IsNullOrEmpty(txt_username.Text))
//    {
//        if (CheckUsername(txt_username.Text.Trim()))
//            lblStatus.Text = "user name already exists please try another name";
//        else
//            lblStatus.Text = "UserName Available";
//    }
//}

//public bool CheckUsername(string user_txt)
//{
//    using (SqlConnection con = new SqlConnection())
//    {
//        con.ConnectionString = "your connection string";
//        con.Open();
//        using (SqlCommand cmd = new SqlCommand("select * from xyz where UserName = @UserID", con))
//        {
//            SqlParameter param = new SqlParameter();
//            param.ParameterName = "@UserID";
//            param.Value = user_txt;
//            cmd.Parameters.Add(param);
//            SqlDataReader reader = cmd.ExecuteReader();
//            if (reader.HasRows)
//                return true;
//            else
//                return false;
//        }
//    }
//}

}



User.cs:
C#
using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TestBlazor.Data;

namespace TestBlazor.Models
{
    [Table("Users")]
    public class User

    {

        [Display(AutoGenerateField = false)]
        public int UserId { get; set; }

        [Display(Name = "UserName")]
        [Required(ErrorMessage = "UserName is required.")]
        public string UserName { get; set; }

        [Display(Name = "Password")]
        [Required]
        [MinLength(8, ErrorMessage = "password must be atleast 8 characters")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Email")]
        [Required(ErrorMessage = "Email is required.")]
        public string Email { get; set; }

        [Display(Name = "Company")]
        [StringLength(255)]
        [Required(ErrorMessage = "Company is required.")]
        [Remote("doesCompanyExist", "Company", HttpMethod = "POST", ErrorMessage = "Company already exists. Please enter a different company.")]
        public string Company { get; set; }

        public User GetRegisteredUser()
        {
            return new User
            {
                UserName = UserName,
                Password = Password,
                Email = Email,
                Company = Company,

            };
        }

    }

}


AppDbContext.cs:

C#
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestBlazor.Models;

namespace TestBlazor.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext()
        {

        }

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=testblazor;Integrated Security=True;");
            }
        }

        //protected override void OnModelCreating(ModelBuilder modelBuilder)
        //{
        //    base.OnModelCreating(modelBuilder);
        //    modelBuilder.Entity<User>()
        //}

        public DbSet<User> User { get; set; }
        public DbSet<Item> Items { get; set; }


    }

}


Login.razor:

Razor
@page "/login"
@using TestBlazor.Models
@inject NavigationManager NavigationManager
@using Microsoft.Data.SqlClient

<br />
<br />
<h3>Login</h3>

<br />

<EditForm Model="@_user" OnValidSubmit="@Check">
    <div class="form-group">
        <p>User name</p>
        <input id="username" class="solid" name="username" placeholder="Your username.." @bind-value="_user.UserName" />
        <ValidationMessage For="@(() => @_user.UserName)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p>Password</p>
        <input type="password" class="solid" id="password" placeholder="Your password.." @bind-value="_user.Password" />
        <ValidationMessage For="@(() => @_user.Password)"></ValidationMessage>
    </div>
    <NavLink href="" class="btn btn-primary">Login</NavLink>
    <br />
    <br />
    <a href="register">Are you a new user? Register now.</a>
</EditForm>


C#
@code {

    private User _user = new User();


    protected string username { get; set; }
    protected string password { get; set; }

    //public void HandleSubmit()
    //{

    //    if (_user.UserName == username && _user.Password == password)
    //    {
    //        NavigationManager.NavigateTo("/");
    //        return;
    //    }
    //    else
    //    {
    //        NavigationManager.NavigateTo("/register");
    //    }

    //}

    public void Check()
    {
        SqlConnection conn = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=testblazor;Integrated Security=True;");
        SqlCommand cmd = new SqlCommand("Select UserName, Password from Users where UserName ='" + username + "'" + "Password ='" + password + "'", conn);

        if (_user.UserName == username && _user.Password == password)
        {
            NavigationManager.NavigateTo("/");
            return;
        }
        else
        {
            NavigationManager.NavigateTo("/register");
        }
    }

}


What I have tried:

I tried to write the following functions in Login.razor page:

C#
public void Check()
    {
        SqlConnection conn = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=testblazor;Integrated Security=True;");
        SqlCommand cmd = new SqlCommand("Select UserName, Password from Users where UserName ='" + username + "'" + "Password ='" + password + "'", conn);

        if (_user.UserName == username && _user.Password == password)
        {
            NavigationManager.NavigateTo("/");
            return;
        }
        else
        {
            NavigationManager.NavigateTo("/register");
        }
    }


public void HandleSubmit()
    {

        if (_user.UserName == username && _user.Password == password)
        {
            NavigationManager.NavigateTo("/");
            return;
        }
        else
        {
            NavigationManager.NavigateTo("/register");
        }

    }



How to call username and password from Register form to Login form? What am I doing wrong?
Posted
Comments
Maciej Los 6-Jul-21 6:00am
   
Your code is SqlInjection vulnerable: SqlCommand cmd = new SqlCommand("Select UserName, Password from Users where UserName ='" + username + "'" + "Password ='" + password + "'", conn);!!!
Member 15270194 6-Jul-21 6:38am
   
Thank you for your reply. What do you mean by that?
Richard Deeming 6-Jul-21 11:31am
   
In addition, NEVER store users' passwords in plain text.

Secure Password Authentication Explained Simply[^]
Salted Password Hashing - Doing it Right[^]
Richard Deeming 6-Jul-21 11:32am
   
And why are you re-inventing the wheel? ASP.NET has several perfectly good authentication systems built-in - for example, ASP.NET Identity[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900