在控制器中验证令牌的不同方法有哪些

时间:2019-07-16 15:02:32

标签: c# .net angular asp.net-web-api jwt

我们要做什么:

BE如何验证令牌?哪个是实现此目标的最佳方法?

personController如何检查令牌?是否带有[Authorize]关键字?我对在互联网上找到的所有信息有些困惑。

我必须在start.cs文件中写些什么,以告诉webapi他们应该在每次请求中都希望有一个令牌?

我们所拥有的:

  • 这是一个新的/空的webapi项目。
  • 我们正在使用.net标准v4.6.1。
  • 项目可以生成令牌(jwt)并发送到FE(角度)。
  • FE将令牌保存在本地存储中,并在每次调用Web api时将其注入。

PD:Webapi将共享资源并处理身份验证工作。我们没有中间件或单独的webapi进行身份验证。

Start.cs:

        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();

            //Enable Cors so that UI can access the API
            // Accept,Content-Type,Origin,X-My-Header
            var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
            cors.SupportsCredentials = true;

            config.EnableCors(cors);

            //  Enable attribute based routing
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "FFR/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            appBuilder.UseWebApi(config);
        }

TokenManager.cs:

public class TokenManager
    {
        //256 - generated on https://passwordsgenerator.net/
        //TODO 2) Move to an external config file?
        private static string _privateKey = "WXNDjpNjSLbYUhTDrf7YQ8sZcMepHf7qWfmqz7dT2uQ9DqJs8N9KqqKBaYmTqtkhWNG5aLxffppc8GV2nSsck9ZyjEC4yhYkpbDnKfwP2ABLcSJgGUFMmTZqMvRfAVdMDF2FnvYmVSxag2WYteWHwTwNrNadV5t4fM925vw4FCKL2jycFqbvQzbzfyxEPWFAcxrXrjCTjcftBBSErAVSFJRce85yL327gG3f2ue8r8BVCG4bWuSvU6jL8veQkqkR";

        private static string _issuer = "test";
        private static string _authority = "test";
        private static int _daysValid = 7;


        public static async Task<string> generateToken(User user)
        {
            string jwtToken = "";

            jwtToken = await CreateJWTAsync(user, _issuer, _authority, _privateKey, _daysValid);

            return jwtToken;
        }

        private static async Task<string> CreateJWTAsync(User user, string issuer, string authority, string symSec, int daysValid)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var claims = await CreateClaimsIdentities(user);

            // Create JWToken
            var token = tokenHandler.CreateJwtSecurityToken(issuer: issuer,
                audience: authority,
                subject: claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddDays(daysValid),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.Default.GetBytes(symSec)), SecurityAlgorithms.HmacSha256Signature));

            return tokenHandler.WriteToken(token);
        }

        private static Task<ClaimsIdentity> CreateClaimsIdentities(User user)
        {
            ClaimsIdentity claimsIdentity = new ClaimsIdentity();
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, user.EmailAddress));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.FullName ?? $"{user.FirstName} {user.LastName}"));

            var roles = Enumerable.Empty<Role>(); 

            foreach (var role in roles)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role.RoleName));
            }

            return Task.FromResult(claimsIdentity);
        }

        //public static async Task<Boolean> verificateToken(string token)
        //{
        //    var tokenHandler = new JwtSecurityTokenHandler();
        //    var securityToken = tokenHandler.ReadToken(token);

        //    securityToken.

        //    return Task.CompletedTask.IsCanceled;
        //}

    }

0 个答案:

没有答案