如何解决在同一项目的WebAPI中实施JWT时,向Asp.net核心MVC添加身份
我有一个带有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 举报,一经查实,本站将立刻删除。