首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Core3MVC对Core的认证

Core3MVC对Core的认证
EN

Stack Overflow用户
提问于 2019-10-03 04:15:35
回答 1查看 450关注 0票数 2

两个独立的项目,DotNet核心3: API和Web。

MVC和Mobile应用程序都只与API对话。

mvc需要对用户进行API身份验证(并且还能够进行google身份验证,并传递给API),这是通过向MVC上的/account/ login /提交的登录页面完成的,后者然后向返回JWT令牌的API打开一个httpclient请求。API将使用JWT来执行来自web应用程序的所有进一步操作。

不幸的是,很多文档只处理API返回令牌,或者使用SPA框架进行身份验证。我正在考虑使用MVC作为客户端。

有一些问题访问返回的JWT声明,并研究如何将其存储在MVC应用程序使用的身份验证cookie中。

API接口控制器 / Auth /

代码语言:javascript
运行
复制
public IActionResult Post()
        {
            //Do auth check here
            if (Request.Form["username"] == "test@test.com" && Request.Form["password"] == "test")
            {

                var authClaims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, "testUsername"),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(ClaimTypes.NameIdentifier, "ID"),
                    new Claim("Name", "testName"),
                    new Claim("Email", "testEmail"),
                };

                var authSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("qwertyuiopasdfghjklzxcvbnm123456"));

                var token = new JwtSecurityToken(
                    issuer: "https://localhost",
                    audience: "https://localhost",
                    expires: DateTime.Now.AddHours(3),
                    claims: authClaims,
                    signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                    );

                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    expiration = token.ValidTo
                });
            }
            return Unauthorized();
        }

MVC上的/account/登录Post操作

代码语言:javascript
运行
复制
            var httpClient = _httpClientFactory.CreateClient("API");

            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("username", username),
                new KeyValuePair<string, string>("password", password)
            });
            var response = await httpClient.PostAsync("https://localhost:{port}/auth", formContent);


            if (response.IsSuccessStatusCode)
            {
                

                var tokenResponse = await response.Content.ReadAsStringAsync();
                var json = JsonDocument.Parse(tokenResponse);

                var token = json.RootElement.GetProperty("token").GetRawText(); 
                var expires = json.RootElement.GetProperty("expiration").GetRawText(); 
                
                var jwt = new JwtSecurityToken(token);
                //Access claims from jwt here, set the identity claims

                //Set cookie authentication for MVC
                var iden = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(iden);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
                //Redirect to account page
             }

标记从API中正确返回,但将给出

有三个段,但没有采用适当的JWS格式。

var jwt = new JwtSecurityToken(token);步骤中出错。

我是不是做错了?我是否应该使用javascript和登录表单提交直接将JWT发送到API,将JWT添加到标头中并将MVC切换到JwtBearer身份验证?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-19 10:56:23

我也遇到了同样的问题,我使用以下代码读取令牌:

代码语言:javascript
运行
复制
jwt = jwt.Replace("Bearer ", string.Empty);
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(jwt);

然后可以使用jwtToken.Claims集合查看声明。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58212217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档