首页 文章

MVC Web Api身份验证失败

提问于
浏览
0

我有两个MVC应用程序,MVC web和MVC web api . MVC应用程序在“http://localhost:8241/ " and MVC web api is running under " http://localhost:8243/”下运行 . 我在MVC应用程序中设置了cookie身份验证 . 这是startup.cs中的代码

app.UseCookieAuthentication(options =>
        {

            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;
            options.AuthenticationScheme = "CookieAuthHRMS";
            options.CookieName = "access_token";

            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            options.SlidingExpiration = true;

            options.LoginPath = new Microsoft.AspNet.Http.PathString("/Account/Login");
            options.LogoutPath = new Microsoft.AspNet.Http.PathString("/Account/Logout");
            options.AccessDeniedPath = new Microsoft.AspNet.Http.PathString("/Account/AccessDenied");

        });

它工作正常 . 我可以使用chrome开发人员工具查看access_token cookie . 所以我想在我的web api项目下添加身份验证 . 所以我在web api项目的Startup.cs下做了完全相同的代码 . 创建名为conjunctioncontroller的控制器来验证web api . 这是代码:

[HttpPost("ConjunctionLI/{username}/{password}")]
    public async Task<bool> ConjunctionLI(string username, string password)
    {

        UsersEntity usrEty = await _usr.findsUsers(username, password);

        if (usrEty != null)
        {
            List<Claim> userClaims = new List<Claim>
            {
                new Claim("userId",usrEty.UserId.ToString()),
                new Claim("EmployeeId",usrEty.EmployeeID),
                new Claim(ClaimTypes.Name, usrEty.UserName),
            };

            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));

            await HttpContext.Authentication.SignInAsync("CookieAuthHRMS", principal);
        }            

        return true;    
    }

在Mvc Web Application中,我在成功登录后调用了连接控制器 . 这是Account controller的Login Action中的代码 .

[HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginViewModel lgvm)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindAsync(lgvm.UserName, lgvm.Password);
            string result;
            if(user!= null)
            {
                //call api service

                using (var client = new HttpClient())
                {

                    string apiSec = @"http://localhost:8243/api/Conjunction/ConjunctionLI/" + lgvm.UserName + "//" + lgvm.Password;

                    HttpResponseMessage response = await client.PostAsync(apiSec, null);
                    response.EnsureSuccessStatusCode();
                    result = await response.Content.ReadAsStringAsync();
                }

                await SignInAsync(user, lgvm.RememberMe);
                return RedirectToAction("Index", "Home");
            }
        }

        return RedirectToAction("AccessDenied","Account");
    }

我将[Authorize]标签放在其中一个web api控制器中但仍然失败 . 即使我使用“await HttpContext.Authentication.SignInAsync(”CookieAuthHRMS“,principal);”像MVC Web应用程序一样,身份验证仍然失败 .

有没有正确的方法呢?如何验证Web api项目?

最好的Rgds,青蛙

1 回答

  • 0

    它是通过在Startup.cs中添加DataProtection中间件来实现的 .

    public void ConfigureServices(IServiceCollection services)
        {
    
            services.AddCors(Configure);                      
    
            services.AddMvc();                                    
    
            services.AddDataProtection();
    
            services.ConfigureDataProtection(configure => {
    
                configure.SetApplicationName("HRMS");
                configure.PersistKeysToFileSystem(new DirectoryInfo(@"C:\shared-auth-ticket-keys\"));               
            });
    
        }
    

相关问题