Web API 身份验证 不记名令牌验证 Bearer Token Authentication
2015-12-16 18:39
696 查看
1. Startup.Auth.cs文件
添加属性
添加静态构造函数
方法ConfigureAuth中添加
2. WebApiConfig.cs文件
方法Register中添加
3. 创建身份验证方法(Web API)
4. 为需要身份验证的控制器或方法添加标记
测试:
在请求头部中添加令牌,格式如下:
Authorization: Bearer boQtj0SCGz2GFGz...
添加属性
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
添加静态构造函数
/// <summary> /// 构造函数 /// </summary> static Startup() { OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); }
方法ConfigureAuth中添加
// 使用不记名身份验证 app.UseOAuthBearerAuthentication(OAuthBearerOptions);
2. WebApiConfig.cs文件
方法Register中添加
config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter("Bearer"));
3. 创建身份验证方法(Web API)
[HttpPost] public async Task<String> Authenticate(string userName, string password) { if (string.IsNullOrEmpty(userAccount) || string.IsNullOrEmpty(password)) { return string.Empty; } // 用户查找失败 User user = await UserManager.FindAsync(userName, password); if (user == null) { return string.Empty; } // 身份验证票证包括角色或者可以换成用户名 var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); if (UserManager.SupportsUserRole) { IList<string> roles = await UserManager.GetRolesAsync(user.Id).ConfigureAwait(false); foreach (string roleName in roles) { identity.AddClaim(new Claim(ClaimTypes.Role, roleName, ClaimValueTypes.String)); } } AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = DateTime.UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(1)); // 返回值 return Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket); }
4. 为需要身份验证的控制器或方法添加标记
[Authorize(Roles = "Admin")] public class UsersController : ApiController { }
测试:
在请求头部中添加令牌,格式如下:
Authorization: Bearer boQtj0SCGz2GFGz...
相关文章推荐
- JD项目的借鉴(1)
- 浅谈GridLayout网格布局
- cobbler自动安装虚拟机linux系统问题
- dbca silent 的区别 11.2.0.3.0 11.2.0.4.0
- C语言二分朝找,拉格朗日朝找
- 嵌入式的一些基础-串行通讯
- NETCTOSS02_资费管理模块
- 接口测试的一些感悟
- 字符设备驱动程序设计
- MySQL的btree索引和hash索引
- 泛型Binary Search Tree实现,And和STL map比较的经营业绩
- Xcode 6.1 做ipa企业级分发(In-House模式)详细步骤
- [ruby]ruby基本数据类型和流程控制
- 软考数据库-无损联接分解
- 详解如何让Android UI设计性能更高效
- C语言排序
- BZOJ-4195 NOI2015Day1T1 程序自动分析 并查集+离散化
- BZOJ-4195 NOI2015Day1T1 程序自动分析 并查集+离散化
- android 的injustdecodebounds
- XGBoost:在Python中使用XGBoost