【WebAPI 验证】给 webapi加上token 验证(包括上传文件方法)

需要给网站开发对接EMI 接口,因此想通过Webapi 进行传递参数,但是由于该方法不太安全,因此不选用,但是记录下该方法的使用。
1,创建WEBAPI 项目,打开nuget 搜索并安装

Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.AspNet.Identity.Owin
Microsoft.Owin.Cors

2,在创建根目录下创建 Startup.cs 文件

using System;
using System.Web.Http;
 
using Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using SqlSugar.WebApi;
 
[assembly: OwinStartup(typeof(WebApi.Startup))]
namespace WebApi
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            ConfigureOAuth(app);
 
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
 
        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"), //该方法用于调用token
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }
}

3,添加验证类 SimpleAuthorizationServerProvider

using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.Owin.Security.OAuth;
using System.Security.Cryptography;
using System.Text;

namespace WebApplication1
{
    /// <summary>
    /// Token验证
    /// </summary>
    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            await Task.Factory.StartNew(() => context.Validated());
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }));

            //*对用户名、密码进行数据校验
            //using (AuthRepository _repo = new AuthRepository())
            //{
            //    IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
            //    if (user == null)
            //    {
            //        context.SetError("invalid_grant", "The user name or password is incorrect.");
            //        return;
            //    }
            //}
            var ws = new localhost.Service();
            var md5Password = MD5Encrypt(context.Password);//e10adc3949ba59abbe56e057f20f883e
            var user = ws.GetUserLogin(true, context.UserName, md5Password);

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("sub", context.Password));
            identity.AddClaim(new Claim("role", "user"));
            //identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));

            context.Validated(identity);

        }
        /// <summary>
        /// 用MD5加密字符串
        /// </summary>
        /// <param name="password">待加密的字符串</param>
        /// <returns></returns>
        public string MD5Encrypt(string password)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] hashedDataBytes;
            hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(password));
            StringBuilder tmp = new StringBuilder();
            foreach (byte i in hashedDataBytes)
            {
                tmp.Append(i.ToString("x2"));
            }
            return tmp.ToString();
        }
    }
}

5,SimpleRefreshTokenProvider

using Microsoft.Owin.Security.Infrastructure;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.OAuth
{
    public class SimpleRefreshTokenProvider : AuthenticationTokenProvider
    {
        private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>();

        /// <summary>
        /// 生成 refresh_token
        /// </summary>
        public override void Create(AuthenticationTokenCreateContext context)
        {
            context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60);

            context.SetToken(Guid.NewGuid().ToString("n"));
            _refreshTokens[context.Token] = context.SerializeTicket();
        }

        /// <summary>
        /// 由 refresh_token 解析成 access_token
        /// </summary>
        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            string value;
            if (_refreshTokens.TryRemove(context.Token, out value))
            {
                context.DeserializeTicket(value);
            }
        }
    }
}

6,创建控制器方法,在方法上面添加:[Authorize]
7,如方法获取文件并保存

[Authorize]
public IHttpActionResult Import()
{
    string msg = string.Empty;
    //接收form表单中提交过来的excel数据表
    var file = HttpContext.Current.Request.Files["File"];
    //限定上传excel扩展名
    string[] extensionName = new string[] { ".XLSX", ".XLS" };
    string serverPath = string.Empty;//上传至服务器的路径
    //首先将excel文件上传至服务器
    //然后转换成从服务器端读取数据插入数据中(浏览器相当于客户端,是无法直接读取远程客户端excel中的数据的)
    //判断excel文件已经跟随表单被传递
    if (!string.IsNullOrWhiteSpace(file.FileName))
    {
        //说明文件已经上传
        string newName = string.Empty;
        //获取excel文件扩展名
        string extName = Path.GetExtension(file.FileName);
        //获取服务器根路径
        string rootPath = AppDomain.CurrentDomain.BaseDirectory;
        //上传值服务器全路径
        string fullPath = string.Empty;
        //判断excel文件是否符合上传标准
        if (extensionName.Contains(extName.ToUpper()))
        {
            //符合上传的文件标准
            newName = Guid.NewGuid().ToString();
            //此时是文件上传至服务器的文件全名
            newName = newName + extName;
            //上传至服务器的路径
            serverPath = "Excels/"; //+ newName;
            fullPath = rootPath + serverPath;
            //判断文件上传文件路径
            if (!Directory.Exists(fullPath))
            {
                //如果不存在,则创建目录
                Directory.CreateDirectory(fullPath);
            }
            //对文件进行上传,读取和插入数据库操作
            try
            {
                //执行上传值服务器操作
                file.SaveAs(HttpContext.Current.Server.MapPath("~/" + serverPath + newName));
                //文件上传至服务器以后,进行读取并导入数据库中
                fullPath = fullPath + newName;

            }
            catch
            {
                //异常时删除上传至服务器的文件
                File.Delete(fullPath);
            }
            finally
            {
                //异常时,手动关闭文件流,并释放内存!
                file.InputStream.Close();
                file.InputStream.Dispose();
            }
        }
        else
        {
            msg = "数据导入失败,文件格式不符合标准,请选择后缀名为:.xlsx,.xls类型文件!";
        }
    }
    else
    {
        msg = "导入数据失败,请在表单中选中要导入excel数据表!";
    }
    return null;
}

8,服务端调用

 using (HttpClient client = new HttpClient())
 {
     var content = new MultipartFormDataContent();
     //添加字符串参数,参数名为qq
     //content.Add(new StringContent("123456"), "qq");

     string path = @"C:\Users\CNRODAI2XX\Desktop\1E91A410.xls";//Path.Combine(System.Environment.CurrentDirectory, "1.png");
     //添加文件参数,参数名为files,文件名为123.png
     content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "1E91A410.xls");
     //content.("A", "B");
     client.DefaultRequestHeaders.Add("a", "1");
     client.DefaultRequestHeaders.Add("b", "2");

     var requestUri = "http://localhost:57711/api/excel/import";
     var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;

     Console.WriteLine(result);
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值