首页 文章

如何在角度中使用keycloak访问令牌

提问于
浏览
0

我已经在我的spring启动应用程序中集成了keycloak适配器,如文档中所述 . 工作流程正在运行 . 最初,我在属性中使用会话令牌存储,但我想摆脱它并且是无状态的 . 所以,我将选项更改为cookie令牌存储 .

我可以看到我的Spring Boot应用程序确实在KEYCLOAK_ADAPTER_STATE cookie(screenshot)中发送了keycloak访问令牌 . 正如所料,它被标记为HTTP cookie .

但是,即使我在查询中打开withCredentials选项,当我查询我的后端时,进一步的角度http请求也不会发送该cookie .

let options : RequestOptions = new RequestOptions();
options.withCredentials = true;
this.http.get('myservice', options)

如何在无状态http调用中使用该令牌?

非常感谢 !

2 回答

  • 0

    我发现了问题 . 到达我的页面的初始请求URL是“/ app / mymodule”,因此keycloak HTTP令牌绑定到/ app路径;但我查询后端的JS http请求是“/ services / myservice”,因此浏览器不会发送cookie,因为根路径不匹配 . 我在/ app / services下移动了我的服务,现在令牌按预期发送,并经过正确验证:) .

  • 0

    使用Interceptors

    HTTP拦截是@ angular / common / http的一个主要特性 . 通过拦截,您可以声明拦截器,以检查和转换从您的应用程序到服务器的HTTP请求 . 相同的拦截器也可以在返回应用程序的路上检查和转换服务器的响应 . 多个拦截器形成一个前向链的请求/响应处理程序从'../auth.service'导入; @Injectable()
    导出类AuthInterceptor实现HttpInterceptor {

    构造函数(private auth:AuthService){}

    拦截(req:HttpRequest <any>,next:HttpHandler){
    //从服务中获取身份验证令牌 .
    const authToken = this.auth.getAuthorizationToken();

    //克隆请求并替换原始标头
    //克隆 Headers ,使用授权进行更新 .
    const authReq = req.clone({
    headers:req.headers.set('Authorization',authToken)
    });

    //将带有 Headers 的克隆请求发送到下一个处理程序 .
    return next.handle(authReq);
    }
    }

    ...

    我认为你应该设置options.withCredentials = true;任何要求

    import { Injectable } from '@angular/core';
    import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, HttpErrorResponse} from '@angular/common/http';
    import {Router} from '@angular/router';
    
    import {Observable} from 'rxjs/Observable';
    import 'rxjs/add/operator/do';
    
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
    
      constructor(private router: Router) { }
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
          withCredentials: true
        });
    
        return next
          .handle(req)
          .do(event => {
            if (event instanceof HttpResponse) {}
          }, (error: any) => {
            if (error instanceof HttpErrorResponse) {
              if (error.status === 401) {
                this.router.navigate(['/login']);
              }
            }
          });
      }
    }
    

相关问题