【问题标题】:Using a single Microsoft authentication in frontend with Angular and in backend with Django REST API在前端和 Angular 中使用单个 Microsoft 身份验证,在后端使用 Django REST API
【发布时间】:2020-02-23 14:51:06
【问题描述】:
我最近制作了一个使用 MS Graph 资源的 Django 应用程序,其中用户以与 this tutorial's 相同的方式进行身份验证。
然后我需要使用 Angular 分离前端,并将我的 Django 应用程序转换为 REST 框架。我设法在 Angular as taught here 中设置了前端身份验证。
我的问题是:如何使用在前端获取的令牌来验证应用程序对我的 Django REST API 的请求,以便后端也可以使用它来查询 MS Graph API?
提前谢谢你们。
【问题讨论】:
标签:
django
angular
django-rest-framework
azure-authentication
【解决方案1】:
前端部分,必须通过{ withCredentials: true }
this.http.get('http://www.example.com/api/auth', { withCredentials: true }).subscribe((resp: any) => {
console.log(resp)
}
我不熟悉 Django,但是,在后端,想法是将SupportCredential 设置为true,也不提供通配符* 以允许来源。您必须提及您的特定前端 url 的路径
【解决方案2】:
好吧,如果您在登录时已经在前端存储了访问令牌,那么您可以在请求的标头中发送访问令牌。在后端,只需检查标头即可。
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'access-token'
})
};
this.http.get('http://www.example.com/api/endpoint', httpOptions).subscribe(res => {
},
err => {
});
供参考:https://angular.io/guide/http