.Net Framework WebApi使用OAuth2.0

参考资料:https://olepetterdahlmann.com/2016/08/08/implement-an-oauth-2-0-authorization-server-using-owin-oauth-middleware-on-asp-net-web-api/  

1.新建webapi项目,并添加以下三个库引用:

Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb

Microsoft ASP.NET Identity Owin

2.App_Start目录下新建类:Startup.Auth.cs

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


namespace YFAPICommon
{
    //Startup.Auth.cs
    public partial class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        static Startup()
        {
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/token"),
                //Provider = new OAuthAppProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
                AllowInsecureHttp = true
            };
        }

        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseOAuthBearerTokens(OAuthOptions);
        }

        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

 

3.新建用来创建Token的控制器:AuthenticateController.cs

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;


namespace YFAPICommon.Controllers
{
    public class LoginInput
    {
        public string account { set; get; }
        public string pass { set; get; }
    }
    public class AuthenticateController : ApiController
    {
        [HttpPost]
        public JObject GetAccessTokenByPass(LoginInput input)
        {

            var tokenExpiration = TimeSpan.FromDays(14);
            ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, "zzzili"));
            identity.AddClaim(new Claim(ClaimTypes.Sid, "1"));

            var props = new AuthenticationProperties()
            {
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };
            var ticket = new AuthenticationTicket(identity, props);
            var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
            JObject tokenResponse = new JObject(
                                        new JProperty("userName", "zzzili"),
                                        new JProperty("access_token", accessToken),
                                        new JProperty("token_type", "bearer"),
                                        new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
                                        new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                                        new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString()));

            return tokenResponse;
        }
    }
}

4.添加Swagger支持:

参看:https://www.cnblogs.com/daxnet/p/6181366.html

5.添加swagger对OAuth的支持,可以在swagger页面上输入token:

在SwaggerConfig.cs文件中修改如下代码:

.Net Framework WebApi使用OAuth2.0_第1张图片

c.EnableApiKeySupport("Authorization", "header");

 

6.项目启动后可以在Swagger页面的右上角api_key处输入access_Token,例如:

Bearer NfHlhFRSf78Ig9cIQ7H2l0P9nxMpaU4H53j_h2PFf2PlqPnIJ**************

7.添加完成后,即可在控制器内对方法添加Auth身份认证:

        [Authorize]
        [HttpPost]
        public string Test1()
        {
            var ident = this.User.Identity;
            return "test";
        }

 

        protected int GetAuthUserId()
        {
            var ident = (ClaimsIdentity)User.Identity;
            return int.Parse(ident.FindFirst(ClaimTypes.Sid).Value);
        }

工程git地址:https://github.com/zzzili/YFAPICommon

你可能感兴趣的:(.NET)