html5 token api,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 classStartup

{public voidConfiguration(IAppBuilder app)

{

ConfigAuth(app);

HttpConfiguration config= newHttpConfiguration();

WebApiConfig.Register(config);

app.UseCors(CorsOptions.AllowAll);

app.UseWebApi(config);

}public voidConfigAuth(IAppBuilder app)

{

OAuthAuthorizationServerOptions option= newOAuthAuthorizationServerOptions()

{

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(newOAuthBearerAuthenticationOptions());

}

}

3.OAuth身份认证,新建SimpleAuthorizationServerProvider类

public classSimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider

{public overrideTask ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)

{

context.Validated();return Task.FromResult(null);

}public override asyncTask GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

{

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*"});//验证用户名密码

AccountService accService = newAccountService();string md5Pwd =LogHelper.MD5CryptoPasswd(context.Password);

IList ul =accService.Login(context.UserName, md5Pwd);if (ul.Count() == 0)

{

context.SetError("invalid_grant", "The username or password is incorrect");return;

}var identity = newClaimsIdentity(context.Options.AuthenticationType);

identity.AddClaim(new Claim("sub", context.UserName));

identity.AddClaim(new Claim("role", "user"));

context.Validated(identity);

}

}

4.新建SimpleRefreshTokenProvider类

public classSimpleRefreshTokenProvider : AuthenticationTokenProvider

{private static ConcurrentDictionary _refreshTokens = new ConcurrentDictionary();///

///生成 refresh_token///

public override voidCreate(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();

}///

///由 refresh_token 解析成 access_token///

public override voidReceive(AuthenticationTokenReceiveContext context)

{stringvalue;if (_refreshTokens.TryRemove(context.Token, outvalue))

{

context.DeserializeTicket(value);

}

}

}

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

[Authorize]public classDefaultController : ApiController

{

[HttpPost]public stringgetPost()

{return JsonConvert.SerializeObject(new { state = 1, msg = "ok"});

}

[HttpGet]

[AllowAnonymous]public string validatePass(stringname)

{return JsonConvert.SerializeObject(new { state = 2, msg = "validatePass_ok"});

}

}

6.传入参数,获取token

86c04b991795c6a8982ea662d488476c.png

7.传入access_token

380be2e040ba9de3296b85abfe59d6c4.png

原文:https://www.cnblogs.com/huangtaiyi/p/11929234.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值