在dot net core MVC中使用Jwt进行简单身份验证

我正在尝试在我的网络核心应用程序中添加JWT验证。 我已经按照这个链接了解了JWT,并且能够通过给出一些像这样的值来生成一个令牌。

var token = new JwtSecurityToken(
  issuer: issuer,
  audience: aud,
  claims: claims,
  expires: expTime,
  signingCredentials: creds
);

编辑:并遵循这个答案,我还JwtBearerAuthentication middleware in my app by adding app.UseJwtBearerAuthentication(new JwtBearerOptions { /* options */ }) to Startup.Configure() method添加了JwtBearerAuthentication middleware in my app by adding app.UseJwtBearerAuthentication(new JwtBearerOptions { /* options */ }) to Startup.Configure() method

现在我卡住了,我怎么能在HTTP头里传递这个令牌? 我在Login上生成这个令牌,但接下来会怎样? 我怎么才能知道智威汤加入并正常工作?

任何形式的帮助将不胜感激。


这是一个可运行的示例,用于ASP.NET Core中的不记名令牌认证。
如何在ASP.NET Core中实现不记名令牌认证和授权

在后端,您可以在此代码后面生成令牌:

[Route("api/[controller]")]
public class TokenAuthController : Controller
{
    [HttpPost]
    public string GetAuthToken(User user)
    {
        var existUser = UserStorage.Users.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password);

        if (existUser != null)
        {
            var requestAt = DateTime.Now;
            var expiresIn = requestAt + TokenAuthOption.ExpiresSpan;
            var token = GenerateToken(existUser, expiresIn);

            return JsonConvert.SerializeObject(new {
                stateCode = 1,
                requertAt = requestAt,
                expiresIn = TokenAuthOption.ExpiresSpan.TotalSeconds,
                accessToken = token
            });
        }
        else
        {
            return JsonConvert.SerializeObject(new { stateCode = -1, errors = "Username or password is invalid" });
        }
    }

    private string GenerateToken(User user, DateTime expires)
    {
        var handler = new JwtSecurityTokenHandler();

        ClaimsIdentity identity = new ClaimsIdentity(
            new GenericIdentity(user.Username, "TokenAuth"),
            new[] {
                new Claim("ID", user.ID.ToString())
            }
        );

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = TokenAuthOption.Issuer,
            Audience = TokenAuthOption.Audience,
            SigningCredentials = TokenAuthOption.SigningCredentials,
            Subject = identity,
            Expires = expires
        });
        return handler.WriteToken(securityToken);
    }
}

在Startup.cs / ConfigureServices方法中

services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
        .RequireAuthenticatedUser().Build());
});

并在Configure方法中添加此代码

app.UseJwtBearerAuthentication(new JwtBearerOptions {
    TokenValidationParameters = new TokenValidationParameters {
        IssuerSigningKey = TokenAuthOption.Key,
        ValidAudience = TokenAuthOption.Audience,
        ValidIssuer = TokenAuthOption.Issuer,
        ValidateIssuerSigningKey = true,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromMinutes(0)
    }
});

在前端,您只需将标记添加到标题中,如下所示:

$.ajaxSetup({
    headers: { "Authorization": "Bearer " + accessToken }
});

要么

$.ajax("http://somedomain/somepath/somepage",{
    headers:{ "Authorization": "Bearer " + accessToken },
    /*some else parameter for ajax, see more you can review the Jquery API*/
});
链接地址: http://www.djcxy.com/p/22409.html

上一篇: Simple Authentication using Jwt in dot net core MVC

下一篇: Windows 10 IoT Core host Web API ASP.Net Core. Possible?