简体   繁体   English

使用 .net 内核 3.1 和 JWT 的授权来自 API 的令牌响应

[英]Authorization with .net core 3.1 with JWT Token response from API

Im new to C# and im struggling with authorization in ASP.Net Core 3.1 MVC web application.I know that there is a lot of instruction on google, i've been reading and watching for 3 days but can not work this out because every instruction i found, it use another way and im really confused.我是 C# 的新手,我在 ASP.Net Core 3.1 MVC web 应用程序中努力授权。我知道谷歌上有很多说明,我已经阅读和观看了 3 天,但无法解决这个问题,因为每条指令我发现,它使用另一种方式,我真的很困惑。

The idea of my system is:我的系统的想法是:

Step 1. I POST username and password to my API and it'll response with JWT Token (if account is correct)第 1 步。我将用户名和密码 POST 到我的 API,它会以 JWT 令牌响应(如果帐户正确)

Step 2. I decode the token and get the username, email, role for my website, set HttpClient header for another requests.第 2 步。我解码令牌并获取用户名 email,我网站的角色,为其他请求设置 HttpClient header。

My problems:我的问题:

  1. How and where to set HttpClient header (with my token) only one time when user login用户登录时如何以及在何处设置 HttpClient header(使用我的令牌)仅一次
  2. How to force users stay at the Login page if they aren't login yet如果用户尚未登录,如何强制用户留在登录页面

Here's my Login method这是我的登录方法

[HttpPost, AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel account)
        {
            string url = "accounts/signin";
            var response = await new HttpClientHelper<LoginViewModel>().PostRequest(url, account);
            var userToken = JsonConvert.DeserializeObject<UserToken>(response);
            Console.Out.WriteLine(userToken.Token);

            if (userToken.Token != null)
            {
                var token = new JwtSecurityToken(jwtEncodedString: userToken.Token);
                var userId = token.Claims.First(c => c.Type == "userId").Value;
                var username = token.Claims.First(c => c.Type == "unique_name").Value;
                var role = token.Claims.First(c => c.Type == "role").Value;
                HttpContext.Session.SetString("token", token.ToString());
                HttpContext.Session.SetString("userId", userId);
                HttpContext.Session.SetString("username", username);
                HttpContext.Session.SetString("role", role);
                return RedirectToAction("Home", "Index");
            }
            return RedirectToAction("Login", "Login");
        }

My model to receive response from api我的 model 接收来自 api 的响应

public class UserToken
    {
        public string Token { get; set; }
        public string ValidFrom { get; set; }
        public string ValidTo { get; set; }
        
    }

FYI: Ive already recived the response from api and got the Token, but ive to set HttpClient header every time i make a request..仅供参考:我已经收到来自 api 的响应并获得了令牌,但是我每次发出请求时都设置 HttpClient header ..

How and where to set HttpClient header (with my token) only one time when user login用户登录时如何以及在何处设置 HttpClient header(使用我的令牌)仅一次

As far as I know, we couldn't set the httpclient header only one time when user login.据我所知,我们无法在用户登录时只设置一次httpclient header。 Normally, we could store the token into session or cookie and then read it from cookie or session when you want to send request to web api. Normally, we could store the token into session or cookie and then read it from cookie or session when you want to send request to web api.

How to force users stay at the Login page if they aren't login yet如果用户尚未登录,如何强制用户留在登录页面

For this requirement, I suggest you could consider using the authentication middleware to achieve your requirement.对于这个要求,我建议您可以考虑使用身份验证中间件来实现您的要求。

You could check the user's session inside this middleware, if this user doesn't contains the session then you could modify the request path to login page.您可以在此中间件中检查用户的 session,如果此用户不包含 session,则可以修改登录页面的请求路径。

More details, you could refer to below example:更多细节,你可以参考下面的例子:

      //Below cods should add after app.usesession in startup.cs Configure method
      app.Use((context, next) =>
        {
            string token = context.Session.GetString("token");
            if (token == null)
            {
                context.Request.Path = "/account/login";
            }               
            return next.Invoke();
        });

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

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