I have gone through many articles and SO Q&A to find the solution to my problem.Below is my requirement
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.
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.