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); } }) })

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM