问题
I have gone through many articles and SO Q&A to find the solution to my problem.Below is my requirement
- As soon as the user browses angular application ,I need to authenticate and get user name and email.
- 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.
- 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.
回答1:
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:
- https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi
- https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-angular/samples/MSALAngularDemoApp
- https://github.com/azure-samples/active-directory-dotnet-native-aspnetcore-v2
- https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1
- https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2
And maybe have a look at Identity Server if you have the time: https://identityserver.io/
来源:https://stackoverflow.com/questions/56051864/how-to-read-jwt-token-from-external-api-to-authenticate-user-and-insert-the-user