简体   繁体   English

如何使用 Microsoft Identity 获取不记名令牌

[英]How to get the bearer token using Microsoft Identity

I have created a controller for Login and there is an endpoint for authentication.我为登录创建了一个控制器,并且有一个用于身份验证的端点。 I am using Microsoft.AspNetCore.Identity;我正在使用Microsoft.AspNetCore.Identity;

在此处输入图像描述

Here is the code for this controller这是此控制器的代码

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

[Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public LoginController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> LoginAsync([FromBody] LoginRequest userLogin)
        {         
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(userLogin.Username, userLogin.Password, isPersistent: false, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                 // code removed for brevity                   
                }               
            }
            return BadRequest();
        }
    }

How do I get the bearer token from result ?如何从result中获取不记名令牌? I wish to return back the token bearer as a response if /api/Login post request is successful.如果 /api/Login 发布请求成功,我希望返回令牌持有者作为响应。

SignInManager<TUser>.PasswordSignInAsync Method Attempts to sign in the specified userName and password combination as an asynchronous operation and return Task<SignInResult> . SignInManager<TUser>.PasswordSignInAsync方法 尝试将指定的用户名和密码组合作为异步操作登录并返回Task<SignInResult> for bearer token use CheckPasswordAsync .对于不记名令牌,请使用CheckPasswordAsync its return a flag indicating whether the given password is valid for the specified user.它返回一个标志,指示给定密码是否对指定用户有效。

_userManager.CheckPasswordAsync(user, model.Password)

if user has valid creadintial then generate the token .如果用户具有有效的密码,则生成令牌

            if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
            {
                var userRoles = await _userManager.GetRolesAsync(user);

                var authClaims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                };

                foreach (var userRole in userRoles)
                {
                    authClaims.Add(new Claim(ClaimTypes.Role, userRole));
                }

               var token = GetToken(authClaims);

                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    expiration = token.ValidTo
                });
            }

Ref: Link1 , Link2 , Link3 , Link4参考: Link1Link2Link3Link4

Depending how you want the client to store the token.取决于您希望客户端如何存储令牌。 If you want to deal with it in the client side you can Return Ok(result.generatedToken) but if you want to set it as a cookie I would recommend you to just Return Ok() but before that you set the cookie in the header of the response.如果你想在客户端处理它,你可以Return Ok(result.generatedToken)但如果你想将它设置为 cookie,我建议你只 Return Ok() 但在此之前你在标题中设置 cookie的回应。 You do this in the server您在服务器中执行此操作

 // append cookie with token to the http response
        CookieOptions? cookieOptions = new()
        {
            HttpOnly = true,
            SameSite = SameSiteMode.Strict,
            Secure = true,
            Expires = ExpirationDate //it has to be a DateTime
        };
        Response.Cookies.Append("token", token, cookieOptions);

the advantage of doing it from the server is that you protect the token from being stolen by XSS injection or other attacks since the token is not accessable from javascript and can only be used in HTTPrequests.从服务器执行此操作的好处是您可以保护令牌不被 XSS 注入或其他攻击窃取,因为令牌无法从 javascript 访问,并且只能在 HTTPrequests 中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM