ASP.NETWebApi实现Token验证

一氧化锰ASP.NETWebApi实现Token验证
基于令牌的认证
我们知道WEB⽹站的⾝份验证⼀般通过session或者cookie完成的,登录成功后客户端发送的任何请求都带上cookie,服务端根据客户端发送来的cookie来识别⽤户。
WEB API使⽤这样的⽅法不是很适合,于是就有了基于令牌的认证,使⽤令牌认证有⼏个好处:可扩展性、松散耦合、移动终端调⽤⽐较简单等等,别⼈都⽤上了,你还有理由不⽤吗?
下⾯我们花个20分钟的时间来实现⼀个简单的WEB API token认证:
Step 1:安装所需的NuGet包:
打开NuGet包管理器控制台,然后输⼊如下指令:
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.1.2
Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0
Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1
Install-Package Microsoft.Owin.Cors -Version 2.1.0
Install-Package EntityFramework -Version 6.0.0
Step 2 在项⽬根⽬录下添加Owin“Startup”类
南艺学分制
1using System;
2using System.Web.Http;
3
4using Owin;
5using Microsoft.Owin;
6using Microsoft.Owin.Security.OAuth;
7using SqlSugar.WebApi;
8
9 [assembly: OwinStartup(typeof(WebApi.Startup))]
10namespace WebApi
11 {
12public class Startup
13    {
14public void Configuration(IAppBuilder app)
15        {
16            HttpConfiguration config = new HttpConfiguration();
17            ConfigureOAuth(app);
18
19            WebApiConfig.Register(config);
20            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
21            app.UseWebApi(config);
22        }
23
24public void ConfigureOAuth(IAppBuilder app)
25        {
26            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
27            {快乐大本营2005年
28                AllowInsecureHttp = true,
29                TokenEndpointPath = new PathString("/token"),
30                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
31                Provider = new SimpleAuthorizationServerProvider()
成本效益分析32            };
33            app.UseOAuthAuthorizationServer(OAuthServerOptions);
34            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
35        }
36    }
37 }
View Code
Step 3:在项⽬根⽬录下添加验证类 SimpleAuthorizationServerProvider,为了简单⽤户的验证部分我们省略掉;
1using System.Threading.Tasks;
2using System.Security.Claims;
3using Microsoft.Owin.Security.OAuth;
4
5namespace WebApi
6 {
7///<summary>
8/// Token验证
9///</summary>
10public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
11    {
12public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
13        {
14await Task.Factory.StartNew(() => context.Validated());
15        }
16
17public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
18        {
19await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }));
20/*孙吉林
21            * 对⽤户名、密码进⾏数据校验
22            using (AuthRepository _repo = new AuthRepository())
23            {
湘潭大学学报
24                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
25
26                if (user == null)
27                {
28                    context.SetError("invalid_grant", "The user name or password is incorrect.");
29                    return;
30                }
31            }*/
32
33var identity = new ClaimsIdentity(context.Options.AuthenticationType);
34            identity.AddClaim(new Claim("sub", context.UserName));
35            identity.AddClaim(new Claim("role", "user"));
36
37            context.Validated(identity);
38
39        }
40    }
41 }
View Code
Step 4:让CORS起作⽤
在ASP.NET Web API中启⽤OAuth的Access Token验证⾮常简单,只需在相应的Controller或Action加上[Authorize]标记
1  [Authorize]
2        [HttpGet, Route("product/getList")]
3public List<Entity.Sys_User> GetProductList()
4        {
5throw new NotImplementedException();
6        }
View Code
Step 5 : 请求 Token
获取token, POST  localhost:23477/token
参数BODY x-www-form-urlencoded 格式:
grant_type=password
username=admin
password=123456
返回状态200 结果为
Step 5 调⽤api
只要在http请求头中加上Authorization:bearer Token就可以成功访问API就成功了:
GET  localhost:58192/api/testapi/testapi
Authorization : bearer T5jF97t5n-rBkWcwpiVDAlhzXtOvV7Jw2NnN1Aldc--
xtDrvWtqLAN9hxJN3Fy7piIqNWeLMNm2IKVOqmmC0X5_s8MwQ6zufUDbvF4Bg5OHoHTKHX6NmZGNrU4mjpCuPLtSbT5bh_gFOZHoIXXIKmqD3Wu1MyyKKNhj9XPEIkd9bl4E9AZ1wAt4dyUxmPV
结果为:

本文发布于:2024-09-21 03:19:09,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/313135.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:验证   实现   客户端   发送   密码   请求
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议