1. Startup.Auth.cs file
Add Property
| 1 |
publicstatic OAuthBearerAuthenticationOptions OAuthBearerOptions { get; privateset; } |
Add a static constructor
| 1234567 |
/// <summary>/// 构造函数/// </summary>staticStartup(){ OAuthBearerOptions = newOAuthBearerAuthenticationOptions();} |
Method added in Configureauth
| 12 |
// 使用不记名身份验证app.UseOAuthBearerAuthentication(OAuthBearerOptions); |
2. WebApiConfig.cs file
Method register to add the
| 12 |
config.SuppressDefaultHostAuthentication();config.Filters.Add(newHostAuthenticationFilter("Bearer")); |
3. Create an authentication method (Web API)
| 123456789101112131415161718192021222324252627282930313233 |
[HttpPost]publicasync Task<String> Authenticate(stringuserName, stringpassword){ if(string.IsNullOrEmpty(userAccount) || string.IsNullOrEmpty(password)) { returnstring.Empty; }<br> // 用户查找失败 User user = await UserManager.FindAsync(userName, password); if(user == null) { returnstring.Empty; } // 身份验证票证包括角色或者可以换成用户名 varidentity = newClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); identity.AddClaim(newClaim(ClaimTypes.NameIdentifier, user.Id.ToString())); if (UserManager.SupportsUserRole) { IList<string> roles = await UserManager.GetRolesAsync(user.Id).ConfigureAwait(false); foreach(stringroleName inroles) { identity.AddClaim(newClaim(ClaimTypes.Role, roleName, ClaimValueTypes.String)); } } AuthenticationTicket ticket = newAuthenticationTicket(identity, newAuthenticationProperties()); varcurrentUtc = DateTime.UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(1)); // 返回值 returnStartup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);} |
4. Add a tag for a controller or method that requires authentication
| 1234 |
[Authorize(Roles = "Admin")]publicclassUsersController : ApiController{} |
Test:
Add a token to the request header in the following format:
Authorization:bearer Boqtj0scgz2gfgz ...
Category: Web API
ASP. NET Web API authentication bearer token verification Bearer token authentication Simple implementation