[英]How to authenticate MVC user login form with web API JWT token?
[英]How to read jwt token from external API to authenticate user and insert the user name and email id in the database
我已经阅读了很多文章和SO Q&A来找到我的问题的解决方案。这是我的要求
我的问题是我在哪里可以在角度应用程序(前端)或asp.net核心(后端)中调用api。 我在asp.net核心端调用,因为我需要用户名和电子邮件来检索和存储。
尝试找出解决方案,但在任何地方,身份验证都是在相同的应用程序级别或使用外部提供商,如谷歌,Twitter等。任何帮助将非常感谢。
如果您在前端获得JTW,则可以在.NET Core后端验证令牌。 从Microsoft获得一些外部验证包,或使用您自己的代码。
如果您想自己验证令牌,请在配置部分执行此操作,如下所示:
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
};
});
...
请记住指定您信任的人(athority和客户端ID),如果您使用azure活动目录 - 您可以从那里获取信息。
它看起来像这样:
"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"
}
对于角度的前端部分,你可以添加一个叫做拦截器的东西,它会将JWT作为你的传出请求的标题附加。
像这样的东西:
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);
}
}
此外,如果您想保护角度应用程序中的页面,请使用称为警卫的内容。
以下是一些资源:
如果您有时间,可以查看Identity Server: https : //identityserver.io/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.