用户在 Django Rest Framework 中按会话注销



我有一个应用程序,其中前端由Angular 6编写,后端由Django Rest Framework编写。

使用以下代码在 frond 上实现用户注销:

@Component({
selector: 'app-logout-modal',
templateUrl: './logout-modal.component.html',
styleUrls: ['./logout-modal.component.scss']
})
export class LogoutModalComponent implements OnInit {
constructor(public thisDialogRef: MatDialogRef<LogoutModalComponent>,
private router: Router,
@Inject(MAT_DIALOG_DATA) public data: any) {
}
ngOnInit() {
}
logoutAndClose(): void {
localStorage.clear();
this.thisDialogRef.close();
this.router.navigateByUrl(RouteUrls.Login);
}
}
class ProfileSettingsViewset(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
@action(detail=False, methods=['post'])
def logout(self, request):
#???
return Response(status=status.HTTP_200_OK)

也就是说,用户实际上并没有注销。

如何在 DRF 上按会话实现用户注销?

要注销用户,您必须实现视图集。

如果您使用基于令牌的身份验证,只需删除令牌即可

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
class Logout(APIView):
def get(self, request, format=None):
# simply delete the token to force a login
request.user.auth_token.delete()
return Response(status=status.HTTP_200_OK)

如果你使用会话身份验证后端,你必须像这样使用 Django 后端注销用户:

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth import logout
class Logout(APIView):
def get(self, request, format=None):
# using Django logout
logout(request)
return Response(status=status.HTTP_200_OK)

然后在网址中:

urlpatterns = [
...
url(r'^logout/', Logout.as_view()),
]

在您的 Angular 组件中必须在删除之前调用对此视图的 Ajax 请求 清除本地存储内容

最新更新