Web API 身份验证 不记名令牌验证 Bearer Token Authentication
2020-11-27 01:55
标签:blog class code c tar color 1. Startup.Auth.cs文件 添加属性 添加静态构造函数 方法ConfigureAuth中添加 2. WebApiConfig.cs文件 方法Register中添加 3. 创建身份验证方法(Web API) 4. 为需要身份验证的控制器或方法添加标记 测试: 在请求头部中添加令牌,格式如下: Authorization: Bearer boQtj0SCGz2GFGz... Web API 身份验证 不记名令牌验证 Bearer Token Authentication,搜素材,soscw.com Web API 身份验证 不记名令牌验证 Bearer Token Authentication 标签:blog class code c tar color 原文地址:http://www.cnblogs.com/wygzs/p/3729054.html
public
static
OAuthBearerAuthenticationOptions OAuthBearerOptions {
get
;
private
set
; }
///
/// 构造函数
///
static
Startup()
{
OAuthBearerOptions =
new
OAuthBearerAuthenticationOptions();
}
// 使用不记名身份验证
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
config.SuppressDefaultHostAuthentication();
config.Filters.Add(
new
HostAuthenticationFilter(
"Bearer"
));
[HttpPost]
public
async Task
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);
}
[Authorize(Roles =
"Admin"
)]
public
class
UsersController : ApiController
{
}
文章标题:Web API 身份验证 不记名令牌验证 Bearer Token Authentication
文章链接:http://soscw.com/index.php/essay/22780.html