问题描述
我有一个带有Web API和MVC的Asp.net核心项目,我正在使用httpclient从MVC访问WebAPI,并且正在对API控制器使用JWT身份验证。
一切正常,除了我现在在我的MVC项目中没有身份验证之外,下面是我的客户端这是我如何从登录控制器中的WebAPI获取JWT令牌(其中包含Claims)
HttpResponseMessage response = await HttpTaskService.PostAsyncData("/api/security",usermodel);
if (response.StatusCode != HttpStatusCode.Unauthorized)
{
string stringJWT = response.Content.ReadAsstringAsync().Result;
JWT jwt = JsonConvert.DeserializeObject<JWT>(stringJWT);
var tokenrev = new JwtSecurityTokenHandler().ReadJwtToken(jwt.Token);
var nameid = tokenrev.Claims.First(c => c.Type == "nameid").Value;
var unique_name = tokenrev.Claims.First(c => c.Type == "unique_name").Value;
var typ = tokenrev.Claims.First(c => c.Type == "typ").Value;
HttpContext.Session.SetString("token",jwt.Token);
''' Now how to add a identity signin here so that i can use [Authorize] in my MVC controllers
}
请注意,我在API和MVC上都有相同的startuo.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddSession();
services.AddMemoryCache();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{ options.TokenValidationParameters = new TokenValidationParameters{ }; });
services.AddDbContext<ApplicationContext>(options =>
options.UsesqlServer(
Configuration.GetConnectionString("DefaultConnection"),b => b.MigrationsAssembly(typeof(ApplicationContext).Assembly.FullName)));
#region Repositories injection
services.AddTransient<IUnitOfWork,UnitOfWork>();
}
我需要在客户端添加身份并使用[Authorize]角色等,我需要将JWT保留在Web api中,因为将来我们将拥有移动端点。
请不要建议使用两个项目,因为我们现在不关注它
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)