用c# webAPI 实现了一个token 服务端应该怎么处理toeken

//登录
public LoginResponse Login(string userName, string userPassword)
        {
            using (WebSiteDbContext dbContext = new WebSiteDbContext())
            {
                LoginResponse result = new LoginResponse();
                User user = dbContext.Users.FirstOrDefault(c => c.Name == userName);
               
                if (user == null)
                {
                    result.Successful = false;
                    result.Message = "用户不存在";
                    result.Token = null;
                    return result;
                }

               
                if (user.Password == userPassword)
                {
                    result.Successful = false;
                    result.Message = "密码错误";
                    result.Token = null;
                    return result;
                }
             
                string accessToken = GenerateToken(user);
                result.Successful = true;
                result.Message = "登录成功";
                result.Token = GenerateToken(user);
                return result;
            }
        }

生成token

        private string GenerateToken(User user)
        {
            string result;
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor();
            tokenDescriptor.Expires = DateTime.UtcNow.AddDays(7);
            tokenDescriptor.Subject = new ClaimsIdentity(new[] {
                    new Claim("userName", user.Name),
                    new Claim("userId",user.Id.ToString())
                });
            var token = tokenHandler.CreateToken(tokenDescriptor);
            result = tokenHandler.WriteToken(token);
            return result;
        }

当前端携带token而来 需要被验证的接口应该如何处理。例如

    [HttpPost]
    public SimpleResponse AddNews(News newsWebsite)
    {
      SimpleResponse result = new SimpleResponse();
      using (WebSiteDbContext dbContext = new WebSiteDbContext())
      {
        dbContext.News.Add(newsWebsite);
        dbContext.SaveChanges();
        result.Successful = true;
        result.Message = "已添加";
        return result;
      }
    }
阅读 2.8k
1 个回答

前置一个 Token 认证中间件

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApi.Helpers;
using WebApi.Services;

namespace WebApi
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // add services to the DI container
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddControllers();

            // configure strongly typed settings object
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            // configure DI for application services
            services.AddScoped<IUserService, UserService>();
        }

        // configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            // custom jwt auth middleware
            app.UseMiddleware<JwtMiddleware>();

            app.UseEndpoints(x => x.MapControllers());
        }
    }
}
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApi.Services;

namespace WebApi.Helpers
{
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly AppSettings _appSettings;

        public JwtMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings)
        {
            _next = next;
            _appSettings = appSettings.Value;
        }

        public async Task Invoke(HttpContext context, IUserService userService)
        {
            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

            if (token != null)
                attachUserToContext(context, userService, token);

            await _next(context);
        }

        private void attachUserToContext(HttpContext context, IUserService userService, string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);

                // attach user to context on successful jwt validation
                context.Items["User"] = userService.GetById(userId);
            }
            catch
            {
                // do nothing if jwt validation fails
                // user is not attached to context so request won't have access to secure routes
            }
        }
    }
}

详见:https://jasonwatmore.com/post...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进