Home > Blockchain >  Blazor WebAssembly with identity server passing username through form
Blazor WebAssembly with identity server passing username through form

Time:12-06

I am new to Blazor WebAssembly. I have a simple page that allows users to register a company. It takes the company name, description and the username. At the moment the username is entered by the user but I want to automatically grab the username of the logged in user and post it without the need of user input. Here is my page:

@page "/companies/create"

@attribute [Authorize]
@inject HttpClient Http
@inject NavigationManager Navigation


<h3>Register your company</h3>
<AuthorizeView>
    Hello, @context.User.Identity.Name!
</AuthorizeView>
<EditForm Model="Companies" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />

    <div class="form-group">
        <label class="control-label">Name</label>
        <InputText @bind-Value="Companies.Name" class="form-control" />
        <ValidationMessage For="@(() => Companies.Name)" />
    </div>

    <div class="form-group">
        <label class="control-label">Description</label>
        <InputText @bind-Value="Companies.Description" class="form-control" />
        <ValidationMessage For="@(() => Companies.Description)" />
    </div>
    <div class="form-group">
        <label class="control-label">Username</label>
        <InputText @bind-Value="Companies.Username" class="form-control"/>
        <ValidationMessage For="@(() => Companies.Username)" />
    </div>


    <button type="submit" class="btn btn-primary">
        <i class="fas fa-save"></i> Register
    </button>
</EditForm>


@code {
    private Sprelo.Shared.Companies Companies { get; set; } = new Sprelo.Shared.Companies();

    private async void HandleValidSubmit()
    {
        try
        {

            var response = await Http.PostAsJsonAsync($"/api/companies", Companies);
            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();
            var companies = JsonConvert.DeserializeObject<Sprelo.Shared.Companies>(content);
            Navigation.NavigateTo($"Companies/edit/{companies.Id}");
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception e)
        {

        }
    }
}

This is my model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sprelo.Shared
{
    public class Companies
    {
        [Key]
        public Guid Id { get; set; }

        [Required]
        public String Name { get; set; }
        public String Description { get; set; }
        public String Username { get; set; }
    }
}

and this is an auto generated API controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Sprelo.Server.Data;
using Sprelo.Shared;

namespace Sprelo.Server.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CompaniesController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public CompaniesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/Companies
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Companies>>> GetCompanies()
        {
            return await _context.Companies.ToListAsync();
        }

        // GET: api/Companies/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Companies>> GetCompanies(Guid id)
        {
            var companies = await _context.Companies.FindAsync(id);

            if (companies == null)
            {
                return NotFound();
            }

            return companies;
        }

        // PUT: api/Companies/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutCompanies(Guid id, Companies companies)
        {
            if (id != companies.Id)
            {
                return BadRequest();
            }

            _context.Entry(companies).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CompaniesExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Companies
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<Companies>> PostCompanies(Companies companies)
        {
            _context.Companies.Add(companies);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetCompanies", new { id = companies.Id }, companies);
        }

        // DELETE: api/Companies/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCompanies(Guid id)
        {
            var companies = await _context.Companies.FindAsync(id);
            if (companies == null)
            {
                return NotFound();
            }

            _context.Companies.Remove(companies);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool CompaniesExists(Guid id)
        {
            return _context.Companies.Any(e => e.Id == id);
        }
    }
}

I have been struggling with this for quite a while, any help would be appriciated!

CodePudding user response:

Inject the AuthenticationStateProvider object into your component like this:

@inject AuthenticationStateProvider authProvider

Override the OnInitialized life cycle method:

protected override void OnInitialized ()
{
    var authenticationStateTask = await 
                          authProvider.GetAuthenticationStateAsync();
                     
    var user = authenticationStateTask.User;

    // Check if the user is authenticated       
    if (user.Identity.IsAuthenticated)
    {
        // Grab the user name and assign it to Companies.Username
        Companies.Username = user.Identity.Name
    }
}
  • Related