WebApi 增長身份驗證 (OAuth 2.0方式)

1,在Webapi項目下添加以下引用:api

Microsoft.AspNet.WebApi.Owinapp

Owinasync

Microsoft.Owin.Host.SystemWebide

Microsoft.Owin.Security.OAuthui

Microsoft.Owin.Security.Cookiesblog

Microsoft.AspNet.Identity.Owintoken

Microsoft.Owin.Cors接口

2, 在項目下新建Startup類,這個類將做爲owin的啓動入口,添加下面的代碼md5

3,修改 Startup類中方法string

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有關如何配置應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkID=316888
            ConfigAuth(app);

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
        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());
        }
    }

4, OAuth身份認證,新建SimpleAuthorizationServerProvider類

    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            AccountService accService = new AccountService();
            string md5Pwd = LogHelper.MD5CryptoPasswd(context.Password);
            IList<object[]> ul = accService.Login(context.UserName, md5Pwd);
            if (ul.Count() == 0)
            {
                context.SetError("invalid_grant", "The username 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);
        }
    }

5, 新建SimpleRefreshTokenProvider類

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

6, 在要加驗證的接口上加上[Authorize]標記

    [Authorize]
    public class EmployeeController : ApiController
    {
        //查詢全部員工
        [HttpGet]
        public IList<UC_Employee> GetAllEmps()
        {
          return new List<UC_Employee>();
        }
    }

7,調用api程序

 

8,傳入參數,獲取token

9,傳入access_token

相關文章
相關標籤/搜索