简体   繁体   中英

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

  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. 在此输入图像描述

My question is where do I call the api either in angular application(front end) or asp.net core(back end). I am calling at asp.net core end as I need user name and email to be retrieved and stored.

  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.

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.

If you get the JTW in the front-end, you can validate the token in the .NET Core back-end. Eather through some external validation package from microsoft, or with your own code.

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.

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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