zoukankan      html  css  js  c++  java
  • asp.net mvc web api Token验证

    一、基于Owin的 OAuth

    1. 在nuget中安装以下工具包
      Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.1.2
      Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0
      Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1
      Install-Package Microsoft.Owin.Cors -Version 2.1.0
      Install-Package EntityFramework -Version 6.0.0
    2. 新建Startup类
      [assembly: OwinStartup(typeof(CSAirWebService.Startup))]
      
      namespace CSAirWebService
      {
          public class Startup
          {
              public void Configuration(IAppBuilder app)
              {
                  // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
                  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"),
                      AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                      Provider = new SimpleAuthorizationServerProvider()
                  };
                  app.UseOAuthAuthorizationServer(OAuthServerOptions);
                 // app.UseOAuthBearerTokens(OAuthServerOptions); //表示 token_type 使用 bearer 方式
                  app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
              }
          }
      }
    3. 新建验证类SimpleAuthorizationServerProvider
          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 identity = new ClaimsIdentity(context.Options.AuthenticationType);
                  identity.AddClaim(new Claim("sub", context.UserName));
                  identity.AddClaim(new Claim("role", "user"));
      
                  context.Validated(identity);
      
              }
          }
    4. 在webapi控制器上将需要认证的Action方法加入特性
             [Authorize]
              [HttpPost]
             
              public string MoniDataHour(QueryModel model)
              {
                  DataTable dt = new DataTable();
                  string Jsonstr = string.Empty;
         
                  
                      string[] StnList = model.MN.Replace("'", "").Split(',');
                      BaseDao dao = new BaseDao();
                      string sql = string.Empty;
                      foreach (var sitem in StnList)
                      {
                          sql += string.Format("select case a.SID  when 'EP01' then 'PM10' when 'EP02' then 'SO2' when 'EP04' then 'NO2' when 'EP06' then 'CO' when 'EP07' then 'O3' when 'EP18' then 'PM25' when 'EP10' then 'TEM' when 'EP11' then " +
                              "'RH' when'EP08' then 'WD' when 'EP09' then 'WS' when 'EP12' then 'PA'  end as SName, a.SStation,b.SStationName,a.SDateTime,a.SValue from t_Samples_{0}_Scd a  join t_SStation b on a.SStation=b.SStation where a.SDateTime='{1}' and a.SID in ('EP01','EP02','EP04','EP06','EP07','EP18','EP09','EP08','EP10','EP11','EP12') union ", sitem, model.DataTime.ToString("yyyy-MM-dd HH:00:00"));
                      }
                      sql = sql.Substring(0, sql.LastIndexOf("union"));
                      dt = dao.CurDbSession.FromSql(sql).ToDataTable();
                   Jsonstr=  JsonConvert.SerializeObject(dt);
                  
                  return Jsonstr;
              }
    5. 方法调用

          前台采用ajax调用,调用前首先要获得token

            $("#btnToken").click(function () {
                $.ajax({
                    'url': 'http://localhost:57035/token',
                    'data': { 'grant_type': 'password', 'username': 'admin', 'password': '123' },
                    'type': 'post',
                    'contentType': "application/json; charset=utf-8",
                    success: function (res) {
                     
                        var da = res.access_token;
                        $("#tokenvalue").text(da);
                    },
                    error: function (res) {
                        console.log(res);
                    }
    
                })
            });

     得到token之后在调用接口

    $("#btnTest").click(function () {
                var data = { 'MN': "'SS4301001','SS4301053'", 'DataTime': '2019-07-01 01:00:00' };
                $.ajax({
                    'url': 'http://15.16.1.131:9001/api/MoniData',
                    'data': JSON.stringify(data),
                    'type': 'post',
                    'dataType':'json',
                    'contentType': "application/json; charset=utf-8",
                    'headers':{"Authorization":"Bearer " +$("#tokenvalue").text}, 
    success:
    function (res)
     { console.log(res); }, error: function (res) { console.log(res); } }) })
  • 相关阅读:
    XMind中使用快捷键自由移动主题
    【转】】win10 更新后,office2016 激活失效的的解决方法
    不能接收具有研究精神的员工,怎么发展。
    【转】一个伟大的公司必有一个伟大的产品
    【转】】审阅史上最烂的代码
    联想和华为
    用python 实现汉诺塔
    系统架构
    产品 or 项目
    【转】我们就必须承认:这个世界上,有很多问题,就是无解的
  • 原文地址:https://www.cnblogs.com/yafuture/p/11317224.html
Copyright © 2011-2022 走看看