使用asp .net core 3 API登录Angular SPA,无需在SPA之外重定向 [英] Login to Angular SPA with asp .net core 3 API without redirect outside of SPA
问题描述
我一直在研究使用 dot net core 3 后端为 API 调用制作 Angular SPA,我想通过登录来保护 API 和 SPA.
I have been looking into making an Angular SPA with dot net core 3 back end for API calls, I would like to secure the API and SPA with a login.
在我发现的所有示例中(例如新的核心 3 Angular 模板,和这个)代码使用身份服务器.我对此没有任何问题,因为在每个示例中,登录过程都会离开 SPA 进行身份验证/登录,然后重定向回 SPA.
In all the examples I have found (such as the new core 3 Angular template, and this) the code uses Identity Server. I have no problem with this EXCEPT for in every example the login process leaves the SPA for authentication/login and then redirects back to the SPA.
我不想离开 SPA.我想从 SPA 内部做所有事情,因为这对我来说是最好的用户体验.在 Microsoft 模板示例中,您将被重定向到另一个页面,其中 SPA 的菜单消失了.如果我这样做,我将不得不维护两个独立的菜单系统.
I don't want to leave the SPA. I want to do everything from inside the SPA as this to me is the best user experience. In the Microsoft template example you get redirected to a different page where the menu from the SPA is gone. If I were to do it this way I would have to maintain two separate menu systems.
所以我的问题是,我如何使用 Angular 7+、asp.net core 3 登录,并且没有任何类型的重定向远离 SPA.如果我不能使用 Identity Server 做到这一点,那么还有其他选择吗?
So my question is, how do I do login with an Angular 7+, asp.net core 3, and not have any type of redirect away from the SPA. If I can't do this with Identity Server, then are there other options?
更新 - 我通过编辑 SPA 应用程序以及默认识别过程的工作方式解决了这个问题,以便我在应用程序中有一个登录表单和一个注册表单.然后安静地进行调用并将登录重定向到后台的 IS,而用户永远不会离开页面.
Update - I solved this by editing the SPA app and how the default identification process works so that I have a login form and a register form in the app. And then quietly do the call and redirect login to IS in the background without the user ever leaving the page.
推荐答案
使用 JWT (JSON Web Token).是 SPA 身份验证的理想解决方案.
Use JWT (JSON Web Token). It is the ideal solution for SPA auth.
.NET Core 端:
.NET Core Side:
- 创建 API 端点以提供 JWT 令牌.IdentityServer 默认发布 JWT(JSON Web 令牌)格式的访问令牌.一个>
- 添加JWT 授权方案到您的 Web API 项目.
- 将
Authorize
属性添加到您要保护的 API.
- Create an API endpoint to provide JWT token. IdentityServer issues access tokens in the JWT (JSON Web Token) format by default.
- Add JWT Authorization Scheme to your web API project.
- Add
Authorize
attribute to APIs you want to protect.
Angular SPA 侧:
Angular SPA Side:
- 使用用户提供的凭据(即电子邮件和密码)调用新创建的 API 并存储它提供的令牌.
- 对于任何受保护 API 的每次 HTTP 调用,HTTP 请求都需要使用 承载架构.
这篇关于使用asp .net core 3 API登录Angular SPA,无需在SPA之外重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!