简体   繁体   English

如何从外部API读取jwt令牌以验证用户并在数据库中插入用户名和电子邮件ID

[英]How to read jwt token from external API to authenticate user and insert the user name and email id in the database

I have gone through many articles and SO Q&A to find the solution to my problem.Below is my requirement 我已经阅读了很多文章和SO Q&A来找到我的问题的解决方案。这是我的要求

  1. As soon as the user browses angular application ,I need to authenticate and get user name and email. 一旦用户浏览角度应用程序,我需要进行身份验证并获取用户名和电子邮件。
  2. The authentication is achieved via external system basically an Api which returns jwt token and after decoded it we will get the info in the form of json. 验证是通过外部系统实现的,基本上是Api,返回jwt令牌,解码后我们将以json的形式获取信息。 在此输入图像描述

My question is where do I call the api either in angular application(front end) or asp.net core(back end). 我的问题是我在哪里可以在角度应用程序(前端)或asp.net核心(后端)中调用api。 I am calling at asp.net core end as I need user name and email to be retrieved and stored. 我在asp.net核心端调用,因为我需要用户名和电子邮件来检索和存储。

  1. So if I am calling api at .net core level ,is it in startup.cs ?,if yes how to decode or consume jwt and fetch the information and insert in db. 所以,如果我在.net核心级调用api,是在startup.cs中吗?,如果是,如何解码或使用jwt并获取信息并插入db。

Trying to find out the solution but everywhere the authentication is done either at the same application level or using external providers like Google,Twitter etc. Any help will be really appreciated. 尝试找出解决方案,但在任何地方,身份验证都是在相同的应用程序级别或使用外部提供商,如谷歌,Twitter等。任何帮助将非常感谢。

If you get the JTW in the front-end, you can validate the token in the .NET Core back-end. 如果您在前端获得JTW,则可以在.NET Core后端验证令牌。 Eather through some external validation package from microsoft, or with your own code. 从Microsoft获得一些外部验证包,或使用您自己的代码。

If you want to validate the token yourself, you do this in the configure section, like so: 如果您想自己验证令牌,请在配置部分执行此操作,如下所示:

public void ConfigureServices(IServiceCollection services)
{
      // authentication with JWT
      services
        .AddAuthentication(o => o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(cfg =>
        {
             cfg.Authority = Configuration["Authentication:Authority"];
             cfg.Audience = Configuration["Authentication:ClientId"];

             cfg.TokenValidationParameters = new TokenValidationParameters()
             {
                 ValidateLifetime = true,
                 ValidateAudience = true,
                 ValidateIssuer = true,
                 RequireExpirationTime = true,
                 RequireSignedTokens = true
             };
        });
...

Remember to specify who you trust (athority and client id), if your using azure active directory - you get the information from there. 请记住指定您信任的人(athority和客户端ID),如果您使用azure活动目录 - 您可以从那里获取信息。

It looks someting like this: 它看起来像这样:

  "Authentication": {
    "Authority": "https://login.microsoftonline.com/xxxxx-3602-4cdc-95de-55459c981858/v2.0",
    "AppIdUri": "https://<your_ad_name>.onmicrosoft.com/xxxxxx-1bf9-4178-a672-4a1ce52d381a",
    "ClientId": "xxxxxx-2095-4202-b75e-ef4f7a0f7ab5"
  }

And for the front-end part in angular, you can add someting called an interceptor, which will append the JWT as a header on your outgoing requests. 对于角度的前端部分,你可以添加一个叫做拦截器的东西,它会将JWT作为你的传出请求的标题附加。

Something like this: 像这样的东西:

import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler
} from "@angular/common/http";
import { Injectable } from "@angular/core";
import { AuthService } from "../auth.service";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const authToken = this.authService.getToken();
    const authRequest = req.clone({
      //adds header authorization: Bearer QWERTYUIOP... to every outgoing request
      headers: req.headers.set("Authorization", "Bearer " + authToken)
    });

    return next.handle(req);
  }
}

Also if you want to protect pages in the angular application, use something called guards. 此外,如果您想保护角度应用程序中的页面,请使用称为警卫的内容。

Here are some resources: 以下是一些资源:

And maybe have a look at Identity Server if you have the time: https://identityserver.io/ 如果您有时间,可以查看Identity Server: https//identityserver.io/

暂无
暂无

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

相关问题 如何使用Web API JWT令牌对MVC用户登录表单进行身份验证? - How to authenticate MVC user login form with web API JWT token? 如何从 jwt 令牌中获取用户 ID? - How to get user id from jwt token? 如何在 Web API C# 中验证来自同一用户的令牌 JWT 令牌 - How to Validate Token JWT Token that it comes from the same User in Web API C# 从访问令牌中读取用户信息(用户ID和名称)。 (Facebook,Twitter,Google,Microsoft) - Read User Info (User Id and Name) from access Token. (Facebook, Twitter, Google, Microsoft) 从 JWT 验证 User.Identity - Authenticate an User.Identity from JWT 从.NET Backend Azure Mobile Service中的身份验证令牌获取名称,电子邮件ID等用户信息 - Get user info like name, email Id etc from authentication token in .NET Backend Azure Mobile Service 如何使用 JWT 令牌授权用户响应 asp net core web api。 何时使用授权标头不记名令牌? - How to use JWT token to authorize user from react to asp net core web api. When to use autorization header bearer token? 如何在不使用JWT的情况下从访问令牌中获取用户数据 - How to get user data from the access token without JWT 实现Identity 2.1 + OWIN OAuth JWT承载令牌时如何从Web API控制器端点进行身份验证 - How to authenticate from Web API controller endpoint when implementing Identity 2.1 + OWIN OAuth JWT bearer token 没有从身份服务器获取用户“电子邮件”作为索赔(来自jwt令牌) - Not getting user “email” as a claim (from jwt token) back from identity server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM