使用app.UseCookieAuthentication与customjwtdataformat,MVC ASPNET

时间:2016-10-17 13:03:53

标签: asp.net-mvc asp.net-core-mvc jwt

我正在使用cookie身份验证为我的MVC应用程序和MVC web api应用程序设置身份验证。这是我的Mvc app的startup.cs代码。

  public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        var secretKey = "esssecret_secretkey!@#$";
        var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

        var tokenValidationParameters = new TokenValidationParameters
        {
            // The signing key must match!
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = signingKey,

            // Validate the JWT Issuer (iss) claim
            ValidateIssuer = true,
            ValidIssuer = "essIssue",

            // Validate the JWT Audience (aud) claim
            ValidateAudience = true,
            ValidAudience = "essAudi",

            // Validate the token expiry
            ValidateLifetime = true,

            // If you want to allow a certain amount of clock drift, set that here:
            ClockSkew = TimeSpan.Zero
        };

        loadServerLink();

        app.UseCookieAuthentication(options =>
        {

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

            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");

        });

        app.UseIISPlatformHandler();

        app.UseMvc(ConfigureRoutes);

        app.UseStaticFiles();

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World -----!");
        });            
    }

这是我在控制器中的登录代码。那很好。

私有异步任务SignInAsync(ApplicationUser用户,bool isPersistent)         {             等待HttpContext.Authentication.SignOutAsync(" CookieAuthHRMS");

        var Cidentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

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

        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims,DefaultAuthenticationTypes.ApplicationCookie));


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

    }

在app.UseCookieAuthentication()中添加两行代码后。我的登录名不会重定向到主页/索引。

  options.CookieName = "access_token";
  options.TicketDataFormat = new CustomJwtDataFormat(SecurityAlgorithms.HMAC_SHA256, tokenValidationParameters);

这是我的控制器代码:

   [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)
            {                    
                await SignInAsync(user, lgvm.RememberMe); //Just stop here and not continue to next line
                return RedirectToAction("Index", "Home");
            }
        }

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

好的我的错误就是等待#34;等待SignInAsync(user,lgvm.RememberMe);&#34;而不是继续&#34;返回RedirectToAction(&#34;索引&#34;,&#34; Home&#34;);&#34;。

这是制作自定义jwt数据格式的参考链接: https://stormpath.com/blog/token-authentication-asp-net-core

最好的Rgds, 青蛙

0 个答案:

没有答案