Following the documentation I have done this.
Login service
function TAux.Login_Token (const AUser : string; const APwd : string) : string;
var
JWT : TJWT;
Scopes : string;
LResult : TLogin_Block;
begin
LResult := DBase.User_Valid (AUser, APwd);
if not LResult.Is_Valid
then raise Exception{EXDataHttpUnauthorized}.Create (err_Invalid_Login);
JWT := TJWT.Create;
try
JWT.Claims.SetClaimOfType<string> ('user', AUser);
if LResult.Is_Admin
then JWT.Claims.SetClaimOfType<Boolean>('admin', True);
if LResult.Is_Super
then JWT.Claims.SetClaimOfType<Boolean>('super', True);
Scopes := 'reader writer';
JWT.Claims.SetClaimOfType<string>('scope', Scopes);
JWT.Claims.Issuer := 'XData Server';
Result := TJOSE.SHA256CompactToken (Srv_Secret, JWT);
finally
JWT.Free;
end;
end;
In Data Module on Server
srvJWT.Secret := Srv_Secret;
On the Client I get the token and save it
procedure TAux.Login_Token (AUser, APwd : string;
ACBFailed : TCB_String;
ACBSuccess : TCB_Boolean);
procedure OnResult (Response : TXDataClientResponse);
var
LRes : string;
begin
if Response.StatusCode = Http_Ok
then begin
LRes := string(TJSObject (Response.Result)['value']);
{$ifdef Use_JWT}
Server.Token := LRes;
{$endif}
ACBSuccess (True);
end
else begin
LRes := '';
ACBFailed ('');
end;
end;
procedure OnError (Error: TXDataClientError);
begin
Log (Error);
ACBFailed ('');
end;
begin
Check_Connection;
xdcAux.RawInvoke (Svc+'Login_Token', [AUser, APwd],
@OnResult, @OnError);
end;
On the client I use the saved token from above in the ConnectionRequest
procedure TServer.ApiConnectionRequest (Args : TXDataWebConnectionRequest);
begin
if Token <> ''
then Args.Request.Headers.SetValue
('Authorization', 'Bearer ' + Token);
end;
I have not set any attributes on the Entities. Fuel, below, is one of the entities.
I am getting
GET http://localhost:2002/chopper/Fuel?$top=0&$inlinecount=allpages 401 (Unauthorized)
{FMessage: 'XData server request error.
Uri: http://localhost:…nlinecount=allpages\nStatus code: 401
Unauthorized', FHelpContext: 0, FJSError: Error: XData server request error.
Uri: http://localhost:2002/chopper/Fuel?$top=0&$inlinecount=allp…, FStack: 'Error: XData server request error.
Uri: http://loc…ttp://localhost:8000/ops/ops_1_0_273.js:56475:34)', FErrorResult: {…}}
Questions
- What have I missed? If I don't set the header on ConnectionRequest ,then it works fine after login.
- Is it somehow, because I am using the same service for Login endpoint as the rest of the Entities?
- Can I set a header of my own name and implement my own security? How do I retrieve the header on the server.