zoukankan      html  css  js  c++  java
  • WebApi的创建,部署,Oauth身份认证(三)

    一,二文章我们讲了WebApi的创建,部署,下面我们来点干货Oauth身份认证

    1.安装所需的NuGet包:

    1.Microsoft.AspNet.WebApi.Owin

    2.Microsoft.Owin.Host.SystemWeb

    3.Microsoft.AspNet.Identity.Owin

    4.Microsoft.Owin.Cors

    5.Microsoft.Owin.Security

    6.Microsoft.Owin.Security.OAuth

    2.在根目录添加 SimpleAuthorizationServerProvider.cs

    using Microsoft.Owin.Security.OAuth;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web;
    
    namespace WebApplication4
    {
        /// <summary>
        /// Token验证
        /// </summary>
        public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
        {
            public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                await Task.Factory.StartNew(() => context.Validated());
            }
    
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }));
                // 对用户名、密码进行数据校验
                string UserName = context.UserName;
                string Password = context.Password;
                if (UserName!= "zhuzhi" || Password != "123456")
                {
                    context.SetError("invalid_grant", "用户名和密码错误!");
                    return;
                }
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));
    
                context.Validated(identity);
    
            }
        }
    }
    

      

    3.在根目录添加 SimpleRefreshTokenProvider.cs

    using Microsoft.Owin.Security.Infrastructure;
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace WebApplication4
    {
        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);
                }
            }
        }
    }

     4.在根目录添加 Startup.cs

    using Microsoft.Owin;
    using Microsoft.Owin.Security.OAuth;
    using Owin;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Http;
    
    [assembly: OwinStartup(typeof(WebApplication4.Startup))]
    namespace WebApplication4
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                HttpConfiguration config = new HttpConfiguration();
    
                //ConfigureOAuth(app);
                ConfigAuth(app);
    
                WebApiConfig.Register(config);
                app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
                app.UseWebApi(config);
            }
            /// <summary>
            /// 普通方法
            /// </summary>
            /// <param name="app"></param>
            public void ConfigureOAuth(IAppBuilder app)
            {
                OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
                {
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                    Provider = new SimpleAuthorizationServerProvider()
                };
                app.UseOAuthAuthorizationServer(OAuthServerOptions);
                app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            }
            /// <summary>
            /// access_token 过期
            /// </summary>
            /// <param name="app"></param>
            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());
            }
        }
    
    }
    

     5.普通调用不加认证

     6.加认证给方法的头部加一个[Authorize]

     7.通过postman获取token(调用的时候webapi的时候上面的网站不能关闭

     8.调用认证的方法

  • 相关阅读:
    [LOJ#6068]. 「2017 山东一轮集训 Day4」棋盘[费用流]
    [BZOJ4842]Delight for a Cat[费用流]
    [HNOI2018]转盘[结论+线段树]
    [LOJ#6066]. 「2017 山东一轮集训 Day3」第二题[二分+括号序列+hash]
    [CF963E]Circles of Waiting[高斯消元网格图优化+期望]
    [CF966F]May Holidays[分块+虚树]
    【JZOJ5088】【GDOI2017第四轮模拟day2】最小边权和 排序+动态规划
    【JZOJ5086】【GDOI2017第四轮模拟day1】数列 折半搜索
    GDOI2017第四轮day1总结
    【51nod1563】坐标轴上的最大团 贪心
  • 原文地址:https://www.cnblogs.com/zhuzhi0819/p/13471437.html
Copyright © 2011-2022 走看看