在项目 asp.net core web api 上添加的一个项目解决方案中,另一个核心 mvc.in api 项目创建了用于登录和注册并获取 jwt token 的 api,并且在 mvc 中我使用 httpClient 使用 api,现在我想通过到标题以获得结果。所以我卡在某个地方帮助我 这是API Controller
[Route("api/Authonticate")]
public class AuthonticateController : Controller
{
private readonly ApplicationDbContext _db;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IConfiguration _configuration;
private readonly RoleManager<IdentityRole> _roleManager;
public BinaryReader CliamTypes { get; private set; }
public AuthonticateController(UserManager<ApplicationUser> userManager,
IConfiguration configuration,
RoleManager<IdentityRole> roleManager,
ApplicationDbContext db)
{
_configuration = configuration;
_userManager = userManager;
_roleManager = roleManager;
_db = db;
}
[HttpGet]
[Route("Role")]
public IQueryable<Object> Role()
{
var userRole = (from user in _db.Users
join userRoles in _db.UserRoles on user.Id equals userRoles.UserId
join role in _db.Roles on userRoles.RoleId equals role.Id
select new { UserName = user.UserName, UserEmail = user.Email, userPhone = user.PhoneNumber, RoleName = role.Name });
var s = userRole.ToList();
return (userRole);
}
[HttpGet]
[Route("GetRoles")]
public List<IdentityRole> GetRoles()
{
return _roleManager.Roles.ToList();
}
[HttpPost]
[Route("Registration")]
public async Task<IActionResult> Register([FromBody]RegisterModel model)
{
var userExist = await _userManager.FindByEmailAsync(model.Email);
if(userExist != null)
{
return StatusCode(StatusCodes.Status500InternalServerError, new Response { status = "Error", message = "User Already Exist" });
}
ApplicationUser user = new ApplicationUser()
{
UserName = model.Name,
Email = model.Email,
PhoneNumber=model.PhoneNumber
};
var result=await _userManager.CreateAsync(user,model.Password);
if (!result.Succeeded)
{
return StatusCode(StatusCodes.Status500InternalServerError, new Response { status = "Error", message = "User Registration Failed!!" });
}
if (!await _roleManager.RoleExistsAsync(Roles.Admin))
await _roleManager.CreateAsync(new IdentityRole(Roles.Admin));
if(!await _roleManager.RoleExistsAsync(Roles.Employee))
await _roleManager.CreateAsync(new IdentityRole(Roles.Employee));
if( model.Role==Roles.Admin)
{
await _userManager.AddToRoleAsync(user, Roles.Admin);
}
else
{
await _userManager.AddToRoleAsync(user, Roles.Employee);
}
return Ok(new Response { status = "Sucess", message = "User Registration Sucessfull!!" });
}
[HttpPost]
[Route("LogIn")]
public async Task<IActionResult> LogIn([FromBody]LogInModel model)
{
var user=await _userManager.FindByEmailAsync(model.Email);
if (user != null && await _userManager.CheckPasswordAsync(user,model.Password))
{
var userRoles = await _userManager.GetRolesAsync(user);
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Email, model.Email),
new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
};
foreach(var userRole in userRoles)
{
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
}
var authSignInKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));
var token = new JwtSecurityToken(
issuer:_configuration["JWT:ValidIssuer"],
audience:_configuration["JWT:ValidAudience"],
expires:DateTime.Now.AddHours(3),
claims:authClaims,
signingCredentials:new SigningCredentials(authSignInKey,SecurityAlgorithms.HmacSha256)
);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo });
}
return Unauthorized();
}
[HttpGet]
[Route("LogOut")]
public async Task<IActionResult> LogOut()
{
await HttpContext.SignOutAsync();
return Ok(new { Message = "You are logged out" });
}
现在是我的 mvc Controller
[Area("Admin")]
public class RegisterController : Controller
{
api _api = new api();
public async Task<IActionResult> Index()
{
List<IdentityRole> roles = new List<IdentityRole>();
HttpClient client = _api.Initial();
HttpResponseMessage res = await client.GetAsync("api/Authonticate/GetRoles");
if (res.IsSuccessStatusCode)
{
var result = res.Content.ReadAsStringAsync().Result;
roles = JsonConvert.DeserializeObject<List<IdentityRole>>(result);
}
ViewBag.RoleList = roles.Select(i => new SelectListItem
{
Value = i.Id.ToString(),
Text = i.Name
});
return View();
}
[HttpPost]
public IActionResult Index(RegisterModel model)
{
HttpClient client = _api.Initial();
var postTalk = client.PostAsJsonAsync("api/Authonticate/Registration", model);
postTalk.Wait();
var result = postTalk.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index", "Home" ,new { Area = "Employee" });
}
return View();
}
[HttpGet]
public IActionResult LogIn()
{
return View();
}
[HttpPost]
public IActionResult LogIn(LogInModel log)
{
HttpClient client = _api.Initial();
var postTalk = client.PostAsJsonAsync("api/Authonticate/LogIn/", log);
postTalk.Wait();
var result = postTalk.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index", "Home", new {Area="Employee"});
}
return View();
}
public async Task<IActionResult> LogOut()
{
HttpClient client = _api.Initial();
HttpResponseMessage res = await client.GetAsync($"api/Authonticate/LogOut");
if (res.IsSuccessStatusCode)
{
return RedirectToAction("Index", "Home", new { Area = "Employee" });
}
return NotFound();
}
}
辅助类是
public HttpClient Initial()
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44324/");
return client;
}
现在我如何将 token 传递给 header
最佳答案
string token="your token";
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
关于asp.net-mvc - 如何在asp.net core mvc header 中传递jwt token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74109108/