asp.net mvc web api Token验证

本文详细介绍在Owin框架下实现OAuth授权的具体步骤,包括安装必要NuGet包、配置Startup类、创建验证类及WebAPI控制器上的认证特性,同时提供前端调用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、基于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); } }) })

 

转载于:https://www.cnblogs.com/yafuture/p/11317224.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值