添加授权时缺少身份验证方案

时间:2020-06-23 02:57:14

标签: c# asp.net-mvc asp.net-core authentication jwt

错误:未指定authenticationScheme,也未找到DefaultChallengeScheme。

我正在创建两个应用程序:WebApi,此工作我遵循以下教程:WebApi Core

运行邮递员时,此功能很好。我遇到的问题是尝试使用Web API创建asp.net核心,我正在关注本教程:Client Side

这就是我所拥有的

两个控制器HomeController,AccountController

AccountController

    public class AccountController : Controller
    {
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public IActionResult Login(AuthenticatedUser user)
        {
            string baseUrl = "http://localhost:8080";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(baseUrl);
            var contentType = new MediaTypeWithQualityHeaderValue("application/json");
            client.DefaultRequestHeaders.Accept.Add(contentType);

            AuthenticatedUser userModel = new AuthenticatedUser();
            userModel.Username = user.Username;
            userModel.Password = user.Password;

            string stringData = JsonConvert.SerializeObject(userModel);
            var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");

            HttpResponseMessage response = client.PostAsync("/Token", contentData).Result;
            string stringJWT = response.Content.ReadAsStringAsync().Result;
            JWT jwt = JsonConvert.DeserializeObject<JWT>(stringJWT);

            HttpContext.Session.SetString("token", jwt.Token);

            ViewBag.Message = "User logged in successfully!";

            return View("Index");
        }
    }

HomeController(没什么特别的,除了我在开始时添加了授权)

   [Authorize]
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
...

在我的startup.cs

ConfigureServices方法

            services.AddMemoryCache();
            services.AddSession();

            services.AddAuthentication(options => {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
                .AddCookie(options =>
                {
                    options.LoginPath = "/Account/Login/";
                   // options.AccessDeniedPath = "/Account/Forbidden/";
                });

并在Configure方法中添加了一些方法

            app.UseSession();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

不确定我缺少什么,我安装了以下软件包,不知道我是否缺少某些东西。

  • Microsoft.AspNet.WebApi.Client
  • Microsoft.AspNetCore.Authentication.OpenIDConnect
  • System.IdentityModel.Tokens.Jwt

我必须说,仅当我将属性[Authorize]放置在家庭控制器上时才出现此问题(没有尝试任何其他位置,但是我感觉我缺少绑定授权属性和方案的东西,但是我没有当然)。

1 个答案:

答案 0 :(得分:0)

对于您的客户端,启动看起来不错。

由于身份验证方案基于Cookie,因此应使用HttpContext.SignInAsync()并使用Cookie存储令牌。

因此,例如,在使用JWT时,通常会有与之相关的声明。您将需要这些声明来构建ClaimsPrincipal对象才能登录。查看下面的更新代码:

注意:切勿在异步方法上使用“ .Result”。另外,考虑使用IHttpClientFactory而不是自己直接创建HttpClient。

        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public async Task<IActionResult> Login(AuthenticatedUser user)
        {
            // This section should be essentially removed. Use IHttpClientFactory 
            string baseUrl = "http://localhost:8080";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(baseUrl);
            var contentType = new MediaTypeWithQualityHeaderValue("application/json");
            client.DefaultRequestHeaders.Accept.Add(contentType);

            string stringData = JsonConvert.SerializeObject(user);
            var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync("/Token", contentData);
            if (response.IsSuccessStatusCode) 
            {
                string stringJWT = await response.Content.ReadAsStringAsync();
                JWT jwt = JsonConvert.DeserializeObject<JWT>(stringJWT);

                var userIdentity = new ClaimsIdentity(token.Claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var userPrincipal = new ClaimsPrincipal(userIdentity);

                // This line here fixes your main issue
                await HttpContext.SignInAsync(userPrincipal);

                HttpContext.Response.Cookies.Append("token", jwt.Token);

                 ViewBag.Message = "User logged in successfully!";
            }

            return View("Index");
        }
    }

注意反序列化令牌,您也可以使用它:

public JwtSecurityToken GetDecodedToken(string token)
{
   return new JwtSecurityTokenHandler( ).ReadJwtToken(token);
}