WebApi Owin OAuth(一)登陆获取access_token

最近需要搭建一个框架提供接口需要支持手机APP、WebForm、WinForm的访问,于是想到使用WebApi,同时考虑到接口的安全认证问题,则采用了Owin OAuth授权认证,Owin OAuth有四种认证方式,这里采用了密码交换Token的认证方式。在这里记录一下整个框架完成的过程。

微软已经对Owin OAuth有了很好的封装,并且创建WebApi项目时整个授权认证框架也一并创建好了。

首先通过VS2015创建一个WebApi,在App_Start目录下有个文件:Startup.Auth.cs它与根目录Startup.cs是partial关系。

Startup.cs最终如下:

using Microsoft.Owin;
using Owin;
using System.Web.Http;
using Microsoft.Owin.Cors;

[assembly: OwinStartup(typeof(SSXLX.WebApi.Startup))]

namespace SSXLX.WebApi
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            //同源策略
            app.UseCors(CorsOptions.AllowAll);
            ConfigureAuth(app);
            app.UseWebApi(config);
        }
    }
}

其中app.UseCors(CorsOptions.AllowAll);是跨域机制,需要引用using Microsoft.Owin.Cors;

Startup.Auth.cs最终如下:

using System;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using SSXLX.WebApi.Providers;

namespace SSXLX.WebApi
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            // 针对基于 OAuth 的流配置应用程序
            var OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Login"),
                Provider = new ApplicationOAuthProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
                //在生产模式下设 AllowInsecureHttp = false
                /*AllowInsecureHttp设置整个通信环境是否启用ssl,
                不仅是OAuth服务端,也包含Client端,
                当设置为false时,若登记的Client端重定向url未采用https,则不重定向*/
                AllowInsecureHttp = true,
                //刷新token
                RefreshTokenProvider = new RefreshOAuthProvider()
            };

            // 使应用程序可以使用不记名令牌来验证用户身份
            app.UseOAuthBearerTokens(OAuthOptions);
        }
    }
}

new PathString("/Login"),默认是"/token",这里改成了"/Login"。

RefreshTokenProvider = new RefreshOAuthProvider()是返回刷新token的凭据值。

在Providers目录会有ApplicationOAuthProvider.cs来验证和生成token的一系列处理:

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System.Linq;
using SSXLX.Api.Interface;
using Microsoft.Practices.Unity;
using SSXLX.Api;
using SSXLX.Api.Entity;

namespace SSXLX.WebApi.Providers
{
    public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
    {
        /// <summary>
        /// 客户端发送了用户的用户名和密码,在这里验证用户名和密码是否正确,
        /// 采用了ClaimsIdentity认证方式,可以把它当作一个NameValueCollection看待
        /// 两个方法同时认证通过才会颁发token
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userInfo = await DependencyInjectionConfig.Containter.Resolve<IUser>().Login(context.UserName, context.Password);
            //判断用户名和密码是否正确
            if (!userInfo.IsOk)
            {
                context.SetError("invalid_grant", userInfo.Message);
                return;
            }

            if (userInfo.Data == null)
            {
                context.SetError("invalid_grant", ResponseCode.DeviceNotMsg);
                return;
            }
            if (userInfo.Data.Password != context.Password.GetMD5())
            {
                context.SetError("invalid_grant", ResponseCode.PwdNotMsg);
                return;
            }

            //ClaimsIdentity认证
            ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

            AuthenticationProperties properties = CreateProperties(context.UserName, userInfo.Data.UserID);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            //认证通过
            context.Validated(ticket);

            await base.GrantResourceOwnerCredentials(context);
        }

        /// <summary>
        /// 把Context中的属性加入到token中
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return Task.FromResult<object>(null);
        }

        /// <summary>
        /// 对third party application 认证,
        /// 为third party application颁发appKey和appSecrect,在此省略了颁发appKey和appSecrect的环节,
        /// 认为所有的third party application都是合法的
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            //表示所有允许此third party application请求
            context.Validated();
            return Task.FromResult<object>(null);
        }

        /// <summary>
        /// 验证重定向url
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        {
            Uri expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
            {
                context.Validated();
            }

            return Task.FromResult<object>(null);
        }

        public static AuthenticationProperties CreateProperties(string userName, string userID)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                { "UserName", userName },
                { "UserID", userID }
            };
            return new AuthenticationProperties(data);
        }

        /// <summary>
        /// 验证refresh token
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
        {
            // Change auth ticket for refresh token requests
            var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

            var newClaim = newIdentity.Claims.Where(c => c.Type == "newClaim").FirstOrDefault();
            if (newClaim != null)
            {
                newIdentity.RemoveClaim(newClaim);
            }
            newIdentity.AddClaim(new Claim("newClaim", "refreshToken"));

            var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
            context.Validated(newTicket);

            return Task.FromResult<object>(null);
        }
    }
}
其中:

            var userInfo = await DependencyInjectionConfig.Containter.Resolve<IUser>().Login(context.UserName, context.Password);
            //判断用户名和密码是否正确
            if (!userInfo.IsOk)
            {
                context.SetError("invalid_grant", userInfo.Message);
                return;
            }


            if (userInfo.Data == null)
            {
                context.SetError("invalid_grant", ResponseCode.DeviceNotMsg);
                return;
            }
            if (userInfo.Data.Password != context.Password.GetMD5())
            {
                context.SetError("invalid_grant", ResponseCode.PwdNotMsg);
                return;
            }

代码是自己判断登陆名密码是否正确的业务代码。

其中:

        public static AuthenticationProperties CreateProperties(string userName, string userID)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                { "UserName", userName },
                { "UserID", userID }
            };
            return new AuthenticationProperties(data);
        }

是认证通过后返回access_token相关信息和自定义用户信息,可以自行添加用户的其他信息如果需要的话。

通过登陆名和密码登陆之后正确返回结果如下(登陆地址:http://localhost:56285/Login):

{"access_token":"QP_vuakMchcTY80ZhbtEfy8ODfOG3NayaLTsqvFWirMB8jS7pfpPwqd3ZNhDAxKeqGlqo_kUFV8Xt8zBT1iy5CKOb61x_u8vozvOtVmVtrdeVXbFfFNhiiGazKmcoGthTui6P1kkTzP4JXlXvF9Z-_s5NgZzOFYN9hZIpYXSJFntcQuXkgNOFL9xdwMpDKPbAOvmz352D-Yets5tUD43ybqNV2zfe3zqwYn6zHITCZrQgmnRqv4vOHnw0ulARPALeV_tBpMU0PfKXUE783KVUg","token_type":"bearer","expires_in":1199,"refresh_token":"52be3102eab84318a2ab131a99c9517c","UserName":"aaa","UserID":"6d609e9e42a34bfc88bedbaaec9675d1",".issued":"Wed, 23 Mar 2016 08:55:18 GMT",".expires":"Wed, 23 Mar 2016 09:15:18 GMT"}

其中access_token是我们调用WebApi业务接口的授权token,expires_in是access_token过期时间(秒),.expires过期时间日期,"token_type":"bearer"Token的传递方式,refresh_token刷新access_token的凭据,UserName和UserID是自定义的用户信息等等。

下一节记录:

1、access_token过期刷新的处理

2、如何使用access_token调用WebApi业务接口

3、WebApi入参的常规习惯问题

3、在WebForm端如何保存access_token及相关信息和Demo打包的相关内容说明

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值