Gett customerid from token in backend Webapi

JJ TT 141 Reputation points
2022-03-23T21:19:47.357+00:00

Goal:
How to get customerid from token when you are located at backend webapi.

Background:
Today, you get your token from backend and it will be sent to frontend. The token alreadly contain the customerid. In order to use customerid as a filtration for linq or similiar you need to send customerid as a parameter.

It is not only a single ActionResult that need to contain customerid as a parameter.

Problem:
It is alot if you have 12 actionresult that has customerid as a parameter. It would be great if you could retrieve the customerid in the backend after you have sent the token to [Authorize(AuthenticationSchemes = "AlphaClient")]. Somehow it would be added in the session or similiar.

It is important that end user retrieve the correct customerid in the backend.

Question:
Is it somehow possible to add customerid in the backend without sending customerid as a parameter?

Info:
I tried following the instruction from this page(https://stackoverflow.com/questions/35849710/webapi-how-to-get-userid-from-token) but it doesn't work.,

Thank you!


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace WebApplication10.Controllers
{
    [AllowAnonymous]
    [ApiController]
    [Route("api/v1/[controller]")]
    public class AuthController : Controller
    {
        [HttpPost("AlphaClientLogin")]
        [AllowAnonymous]
        public ActionResult<ClientToken> AlphaClientLogin([FromBody] User user)
        {
            if (user.Username == "userAlpha" && user.Password == "123")
            {
                return AlphaTokenService.GenerateToken(user);
            }
            else
            {
                return Unauthorized(new { message = "Invalid Username or password" });
            }
        }
    }


    [Route("api/v1/[controller]")]
    [ApiController]
    [Authorize(AuthenticationSchemes = "AlphaClient")]
    public class TestController : Controller
    {
        /// <summary>
        /// https://localhost:38744/api/v1/Test/Test2
        /// </summary>
        /// <returns></returns>
        [HttpGet("Test2", Name = "Test2")]
        public async Task<ActionResult<Int32>> Test2(string customerid)
        {
            return 3;
        }
    }



    public class ClientToken
    {
        public string Token { get; set; }
        public DateTime DateExpiration { get; set; }
    }


    public class AlphaTokenService
    {
        public static ClientToken GenerateToken(User user)
        {
            string secret = "myunlegiveblealphasecret";
            string audience = "AudienceClientAlpha";
            string issuer = "IssuerClientAlpha";

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var credenciais = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
            var expiration = DateTime.UtcNow.AddHours(2);
            var claims = new[]{
                                    new Claim("customerid", "123455666"),
                                    new Claim(ClaimTypes.Name, user.Username.ToString()),
                                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                                };

            JwtSecurityToken token = new JwtSecurityToken(
                                                           audience: audience
                                                          , issuer: issuer
                                                          , claims: claims
                                                          , expires: expiration
                                                          , signingCredentials: credenciais);

     

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication10", Version = "v1" });
    });


    services.AddAuthentication().AddJwtBearer("AlphaClient", options => {
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("myunlegiveblealphasecret")),
            ValidAudience = "AudienceClientAlpha",
            ValidIssuer = "IssuerClientAlpha",
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };
    });
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,180 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,136 Reputation points
    2022-03-23T23:01:14.883+00:00

    The syntax is...

    [HttpGet]
    [Authorize]
    public IActionResult GetAll()
    {
        var user = User?.Identity?.Name;
        var id = User?.Claims.FirstOrDefault(c => c.Type == "customerid")?.Value;
    
        return Ok(new { username = user, customerid = id });
    }
    

0 additional answers

Sort by: Most helpful