ASP.NET WebApi 實現Token驗證


基於令牌的認證

    我們知道WEB網站的身份驗證一般通過session或者cookie完成的,登錄成功后客戶端發送的任何請求都帶上cookie,服務端根據客戶端發送來的cookie來識別用戶。

    WEB API使用這樣的方法不是很適合,於是就有了基於令牌的認證,使用令牌認證有幾個好處:可擴展性、松散耦合、移動終端調用比較簡單等等,別人都用上了,你還有理由不用嗎?

    下面我們花個20分鍾的時間來實現一個簡單的WEB API token認證:

Step 1:安裝所需的NuGet包:

打開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

 

Step 2 在項目根目錄下添加Owin“Startup”類

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"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }
}

 

Step 3:在項目根目錄下添加驗證類 SimpleAuthorizationServerProvider,為了簡單用戶的驗證部分我們省略掉;

using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.Owin.Security.OAuth;
 
namespace WebApi
{
    /// <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 identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
 
            context.Validated(identity);
 
        }
    }
}

 

Step 4:讓CORS起作用

在ASP.NET Web API中啟用OAuth的Access Token驗證非常簡單,只需在相應的Controller或Action加上[Authorize]標記

        [Authorize]
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";
 
            return View();
        }

 

Step 5 : 請求 Token

獲取token, POST   http://localhost:23477/token

參數BODY x-www-form-urlencoded 格式:

grant_type=password&username=admin&password=123456

返回狀態200 結果為

Step 5 調用api

只要在http請求頭中加上Authorization:bearer Token就可以成功訪問API就成功了:

GET   http://localhost:58192/api/testapi/testapi

Authorization : bearer 

T5jF97t5n-rBkWcwpiVDAlhzXtOvV7Jw2NnN1Aldc--xtDrvWtqLAN9hxJN3Fy7piIqNWeLMNm2IKVOqmmC0X5_s8MwQ6zufUDbvF4Bg5OHoHTKHX6NmZGNrU4mjpCuPLtSbT5bh_gFOZHoIXXIKmqD3Wu1MyyKKNhj9XPEIkd9bl4E9AZ1wAt4dyUxmPVA_VKuN7UvYJ97TkO04XyGqmXGtfVWKfM75mNVYNhySWTg

 

  結果為:

 

轉自:https://www.cnblogs.com/dukang1991/p/5627584.html

轉自:https://blog.csdn.net/qq_32688731/article/details/80897563


免責聲明!

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



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