目标:
当您位于后端webapi时,如何从令牌中获取customerid。
背景:
今天,您从后端获得代币,并将其发送到前端。令牌已包含customerid。为了使用customerid作为linq或类似程序的过滤,您需要将customerid作为参数发送。
不仅仅是单个ActionResult需要包含customerid作为参数。
问题:
如果您有12个以customerid为参数的actionresult,那就太多了。如果您可以在将令牌发送到[Authorize(AuthenticationSchemes="AlphaClient"(]后在后端检索customerid,那将是一件很棒的事情。不知怎的,它会被添加到会话或类似的内容中。
最终用户在后端检索正确的customerid非常重要。
问题:
是否可以在后端添加customerid而不将customerid作为参数发送?
信息:
我尝试遵循此页面中的说明(WebAPI-如何从令牌中获取UserID(,但不起作用。,
谢谢!
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);
ClientToken clientToken = new ClientToken();
clientToken.Token = new JwtSecurityTokenHandler().WriteToken(token);
clientToken.DateExpiration = expiration;
return clientToken;
}
}
public class User
{
public string Username { get; set; }
public string Password { get; set; }
}
}
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
};
});
}
我得到了一个人的帮助。
[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 });
}