Get Bearer Token when login in

.NET 专栏收录该内容
201 篇文章 0 订阅
Get Bearer Token when
Login in 
[HttpPost]
    [AllowAnonymous]
    [Route("api/account/login")]
    public HttpResponseMessage Login(LoginBindingModel login)
    {
        // todo: add auth
        if (login.UserName == "a@a.com" && login.Password == "a")
        {
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, login.UserName));
---------------------------------------------------------------------------------------------------------------------------
            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); 
---------------------------------------------------------------------------------------------------------------------------
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent<object>(new { UserName = login.UserName, AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket) }, Configuration.Formatters.JsonFormatter) }; } return new HttpResponseMessage(HttpStatusCode.BadRequest); }
 
 
 

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
{
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

lglgsy456

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值