WebApi使用Token(OAUTH 2.0方式)

摘要:
1.添加对Microsoft.AspNet.WebApi.OwinMicrosoft.Owin.Host.SystemWebMicrosoft.Owin.Security.AuthMicrosoft.Owin.Security.CookiesMicrosoft.AspNet.Identity.OwinMicrosoft.Owin的引用。项目中的Cors2。创建新的Startup类publicclassS

1.在项目中添加引用

Microsoft.AspNet.WebApi.Owin

Microsoft.Owin.Host.SystemWeb

Microsoft.Owin.Security.OAuth

Microsoft.Owin.Security.Cookies

Microsoft.AspNet.Identity.Owin

Microsoft.Owin.Cors

2.新建Startup类

 public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            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());
        }
    }

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

4.新建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);
        }
    }
}

5.在要加验证的接口上加上[Authorize]标记

 [Authorize]
    public class DefaultController : ApiController
    {
        [HttpPost]
        public string getPost()
        {
            return JsonConvert.SerializeObject(new { state = 1, msg = "ok" });
        }

        [HttpGet]
        [AllowAnonymous]
        public string validatePass(string name)
        {
            return JsonConvert.SerializeObject(new { state = 2, msg = "validatePass_ok" });
        }
    }

6.传入参数,获取token

WebApi使用Token(OAUTH 2.0方式)第1张

7.传入access_token

WebApi使用Token(OAUTH 2.0方式)第2张

参考原文地址:https://www.cnblogs.com/lnice/p/6857203.html

免责声明:文章转载自《WebApi使用Token(OAUTH 2.0方式)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇使用ADB上传、下载文件和安装软件的方法Qt---ToolBox自由伸展下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

springboot后端实现条件查询,要配合使用mybatis

packagecn.com.dyg.work.sqlgen; importcn.com.dyg.work.common.exception.DefException; importcn.com.dyg.work.common.utils.CamelAndUnderLineConverter; importcom.alibaba.fastjson.JSON...

shiro 框架基本讲解【转载】

shiro 框架基本讲解【转载】 什么是权限管理: 基本上涉及到用户参与的系统都要进行权限管理,权限管理属于系统安全的范畴,权限管理实现对用户访问系统的控制,按照安全规则或者安全策略控制用户可以访问而且只能访问自己被授权的资源。 权限管理包括用户身份认证和授权两部分,简称认证授权。对于需要访问控制的资源用户首先经过身份认证,认证通过后用户具有该资源的访问...

浅尝SignalR

垂涎WebSocket已经很久了,终于有了学习的机会。 对于ASP.NET,试着用了下Fleck,比较方便,但是问题多多,一个挂则全挂,没时间去研究。 之后,找到了SignalR,看大神们的博客后感觉简单且好用。 原理神马的,后面再来贴,先记录下Demo小激动一下。 首先,创建一个MVC项目SignalRDemo。 接着,引入SignalR: 引用完成后...

python之SQLAlchemy

ORM介绍 orm英文全称object relational mapping,就是对象映射关系程序,简单来说我们类似python这种面向对象的程序来说一切皆对象,但是我们使用的数据库却都是关系型的,为了保证一致的使用习惯,通过orm将编程语言的对象模型和数据库的关系模型建立映射关系,这样我们在使用编程语言对数据库进行操作的时候可以直接使用编程语言的对象模型...

JQuery EasyUI datagrid 批量编辑和提交

前台主要代码: <script type="text/javascript"> $(function() { var $dg = $("#dg"); $dg.datagrid({ url : "servlet/list", width : 700,...

微信开放平台微信公众平台微信小程序openid合法性验证

我们获得了微信用户的openid,往往要把openid保存到服务器中的数据库里。有些场景需要检验openid的合法性,官方给了相应的验证接口如下: https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=openid 填入正确的 ACCESS_TOKEN 和 open...