• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

asp.netmvcwebapiToken验证

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、基于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)
 (res) { console.log(res); } }) })

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap