zoukankan      html  css  js  c++  java
  • WebApi使用Token(OAUTH 2.0方式)

    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

    7.传入access_token

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

  • 相关阅读:
    javascript/jquery操作cookie
    更改IE/FireFox查看源代码的默认编辑器,比如notepad++
    javascript refresh page 几种页面刷新的方法
    C# Enum,Int,String的互相转换 枚举转换
    js中两个感叹号的作用
    JQuery操作iframe
    JQuery判断一个元素下面是否有内容或者有某个标签
    Meta标签详解
    五一放假回校,真爽
    ASP.NET错误处理(一)摘自MSDN
  • 原文地址:https://www.cnblogs.com/huangtaiyi/p/11929234.html
Copyright © 2011-2022 走看看