1. 程式人生 > >asp.net Web API 身份驗證 不記名令牌驗證 Bearer Token Authentication 簡單實現

asp.net Web API 身份驗證 不記名令牌驗證 Bearer Token Authentication 簡單實現

驗證 tca star ati manager ace .com return public

1. Startup.Auth.cs文件

添加屬性

1 public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }

添加靜態構造函數

1 2 3 4 5 6 7 /// <summary> /// 構造函數 /// </summary> static Startup() { OAuthBearerOptions = new
OAuthBearerAuthenticationOptions(); }

方法ConfigureAuth中添加

1 2 // 使用不記名身份驗證 app.UseOAuthBearerAuthentication(OAuthBearerOptions);

2. WebApiConfig.cs文件

方法Register中添加

1 2 config.SuppressDefaultHostAuthentication(); config.Filters.Add(
new HostAuthenticationFilter("Bearer"));

3. 創建身份驗證方法(Web API)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 [HttpPost] public async Task<String> Authenticate(string userName, string
password) { if (string.IsNullOrEmpty(userAccount) || string.IsNullOrEmpty(password)) { return string.Empty; }<br> // 用戶查找失敗 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. 為需要身份驗證的控制器或方法添加標記

1 2 3 4 [Authorize(Roles = "Admin")] public class UsersController : ApiController { }

測試:

在請求頭部中添加令牌,格式如下:

Authorization: Bearer boQtj0SCGz2GFGz...

分類: Web API

asp.net Web API 身份驗證 不記名令牌驗證 Bearer Token Authentication 簡單實現