基于WebApi的OAuth2验证

1.    环境:vs2013,Framework 4.5

2.    文件结构

3.    需引入的dll

Microsoft.AspNet.Identity.Owin.dll

2.2.1.40403|2.2.1.40403

 

Microsoft.Owin.Cors.dll

2.020911.395|2.0.0

 

Microsoft.Owin.dll

3.0.40213.64|3.0.1

编译或调试时添加的

Microsoft.Owin.Host.SystemWeb.dll

3.0.40213.64|3.0.1

 

Microsoft.Owin.Security.Cookies.dll

3.0.40213.64|3.0.1

 

Microsoft.Owin.Security.dll

3.0.10213.64|3.0.1

编译或调试时添加的

Microsoft.Owin.Security.OAuth.dll

3.0.40213.64|3.0.1

 

Newtonsoft.Json.dll

6.0.4.17603|6.04.17603

默认添加的版本大致为4.5,运行后会报错

Owin.dll

1.0.0.0|1.0

 

 

 

4.    代码

1)         添加Owin Startup

 

using System;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security.OAuth;
using Owin;
using WebApi4.OAuth;


[assembly: OwinStartup(typeof(WebApi4.Startup))]

namespace WebApi4
{
    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());
        }
    }
}
View Code

 

2)         添加验证类SimpleAuthorizationServerProvider

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

namespace WebApi4.OAuth
{
    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);
        }
    }
}
View Code

 

3)         添加SimpleRefreshTokenProvider

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

namespace WebApi4.OAuth
{
    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);
            }
        }
    }
}
View Code

 

4)         添加业务代码

a)     控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using WebApi4.Models;

namespace WebApi4.Controllers
{
    [Authorize]
    public class EmployeeController : ApiController
    {
        //查询所有员工
        [HttpGet]
        public IList<UC_Employee> GetAllEmps()
        {
            return new List<UC_Employee>();
        }
    }
}
View Code

 

b)     添加模型类 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApi4.Models
{
    public class UC_Employee
    {
    }
}
View Code

 

5)         修改Web.config配置文件(

  

5.    调试

1)         无验证情况访问

 

2)         授权

 

3)         验证成功

 

 

6.    参考资料

1)         https://www.cnblogs.com/lnice/p/6857203.html

转载于:https://www.cnblogs.com/fcn26/p/9219589.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值