c# - 通过 Angular 11 应用程序和 .Net 4.7.2 Web API 正确使用 CAS 身份验证
问题描述
在我第一次接触 Angular 时,我有一个使用 Angular 前端和后端的 .NET Web API 的现有应用程序。预先存在的应用程序正在使用一种登录方案,其中本地帐户存储在数据库中。我正在尝试修改此应用程序以使用我们组织的 CAS 服务器进行身份验证。
到目前为止我所做的工作是基于这里找到的指导:https ://www.blinkingcaret.com/2018/10/10/sign-in-with-an-external-login-provider-in-an-angular -asp-net-core 提供的应用程序/
到目前为止,我已经做了一些关键的改变。在 authentication.service.ts 中,我修改了登录函数以指向我在服务器上的新操作
login(){
this.document.location.href = this.casUrl + "login"
}
在我新添加的 CAS 控制器中,我有以下操作。
public ActionResult Login() {
return new ChallengeResult("CAS");
}
public ActionResult HandleLogin() {
var claimsId = (ClaimsIdentity)User.Identity;
//Do things with claims, check against DB, etc
}
private class ChallengeResult : HttpUnauthorizedResult {
//sets the RedirectUri to HandleLogin, fires the Challenge in the ExecuteResult function
}
到目前为止,事情似乎表现良好。User.Identity 填充正确,因此我可以从数据库中检索相应的用户。我也可以构造一个 LoginResponse 对象,尽管目前没有对它做任何事情。此 LoginResponse 包含在应用程序的另一部分中生成的令牌,并且似乎是 JWT。
此时,我不知道如何将我的 LoginResponse 传输回 Angular。
在使用本地帐户的原始实现中,向 API 端点发送了一个帖子,并将响应通过管道传送到需要它的地方。
return this.http.post(this.apiUrl + 'auth/login',
//parameters
), headers).pipe(
map((user:LoginResponse) => {
//do stuff with LoginResponse
}));
反过来,调用此服务的组件订阅其返回值。
我的想法是在组件的 init 中调用一个新函数。它将采取的第一个操作是转到我的 CasUrl 端点并请求使用 User.Identity 和 DB 查找构造的 LoginResponse。不幸的是,在所有后续调用服务器时,身份都是空的。它似乎不会在请求之间持续存在。
另一个可能相关的注意事项:我的 Web API 解决方案在 localhost:46000 上通过 Visual Studio 运行,而 Angular 应用程序在 localhost:4200 上的 VSCode 中运行。
使用此应用程序获得外部身份验证我缺少什么?是否可以有一个角管道或订阅等待来自外部网站的结果?
解决方案
如果我理解正确,您将完全重定向到您的 CAS 服务器,使用location.href
该服务器(在成功验证后)重定向到您的路由/登录。因此 /login 应该使用完整的 Angular 站点响应或重定向到具有 HttpStatus 302 的站点。服务器生成的会话 cookie 然后可以用于对后端的进一步请求。AccountService.ts 可以通过调用 api 检查用户是否经过身份验证。api/home/isAuthenticated
此请求应自动附加新收集的会话 cookie。
推荐阅读
- regex - 正则表达式 - 如何创建一个表达式来呈现用逗号括起来的结果?
- django - 我想知道如何使用模型 id 在 django 中获取正确的数据
- reactjs - 在 React 中函数 no param 和 has parm work 有什么区别?
- snowflake-cloud-data-platform - 使用 Liquibase 创建雪花存储过程
- ios - WKWebView - 对 iframe 中加载的外部 URL 的离线支持
- r - 在 R 中更改多个 .csv 文件中的同一列
- javascript - 招聘管理系统的类图
- python - 安装所有扩展后,我无法在我的 vs 代码中在 django 中创建单个项目
- javascript - 这个符号在javascript中是什么意思?
- iot - 通过 ThingPark 社区网络服务器接收 LoRaWAN 上行链路消息