1. 程式人生 > 實用技巧 >WebApi的建立,部署,Oauth身份認證(三)

WebApi的建立,部署,Oauth身份認證(三)

一,二文章我們講了WebApi的建立,部署,下面我們來點乾貨Oauth身份認證

1.安裝所需的NuGet包:

1.Microsoft.AspNet.WebApi.Owin

2.Microsoft.Owin.Host.SystemWeb

3.Microsoft.AspNet.Identity.Owin

4.Microsoft.Owin.Cors

5.Microsoft.Owin.Security

6.Microsoft.Owin.Security.OAuth

2.在根目錄新增 SimpleAuthorizationServerProvider.cs

using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;

namespace WebApplication4
{
    /// <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[] { "*" }));
            // 對使用者名稱、密碼進行資料校驗
            string UserName = context.UserName;
            string Password = context.Password;
            if (UserName!= "zhuzhi" || Password != "123456")
            {
                context.SetError("invalid_grant", "使用者名稱和密碼錯誤!");
                return;
            }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
    }
}

  

3.在根目錄新增SimpleRefreshTokenProvider.cs

using Microsoft.Owin.Security.Infrastructure;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication4
{
    public class SimpleRefreshTokenProvider : AuthenticationTokenProvider
    {
        
private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>(); /// <summary> /// 生成 refresh_token /// </summary> public override void Create(AuthenticationTokenCreateContext context) { context.Ticket.Properties.IssuedUtc
= DateTime.UtcNow; context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60); context.SetToken(Guid.NewGuid().ToString("n")); _refreshTokens[context.Token] = context.SerializeTicket(); } /// <summary> /// 由 refresh_token 解析成 access_token /// </summary> public override void Receive(AuthenticationTokenReceiveContext context) { string value; if (_refreshTokens.TryRemove(context.Token, out value)) { context.DeserializeTicket(value); } } } }

4.在根目錄新增 Startup.cs

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

[assembly: OwinStartup(typeof(WebApplication4.Startup))]
namespace WebApplication4
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            //ConfigureOAuth(app);
            ConfigAuth(app);

            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
        /// <summary>
        /// 普通方法
        /// </summary>
        /// <param name="app"></param>
        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());
        }
        /// <summary>
        /// access_token 過期
        /// </summary>
        /// <param name="app"></param>
        public void ConfigAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"), //獲取 access_token 授權服務請求地址
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), //access_token 過期時間
                Provider = new SimpleAuthorizationServerProvider(), //access_token 相關授權服務
                RefreshTokenProvider = new SimpleRefreshTokenProvider() //refresh_token 授權服務
            };
            app.UseOAuthAuthorizationServer(option);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }

}

 5.普通呼叫不加認證

6.加認證給方法的頭部加一個[Authorize]

7.通過postman獲取token(呼叫的時候webapi的時候上面的網站不能關閉

8.呼叫認證的方法