Search code examples
restdelphirestful-authentication

REST-Server proper place for authentication


I have a REST-Client Standalone Desktop-Application in which I can enter a URL and can choose what kind of REST Method I want to execute (POST, GET, PUT etc.)

the client primarily serves the function to send a Body-Message (XML-Format). inside the message all the necessary information to handle the message is contained.

the client also has a Basic authenticator so each Request is also sending a Username and password.

With the help of the Delphi XE8 Application Wizard I created a simple Standalone Firemonkey REST-Server with Authentication and Authorization.

When I send a Request from the Client-Application then my Server is able to recieve that Request inside the "WebModuleDefaultAction"-function which has been added by the Wizard.

What I would like to know is wether or not this is the proper place to check the Authorization of the Request for legitimicy.

It would look like this:

procedure TWebModule1.WebModuleDefaultAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
  s:string;
  Username:string;
  Password:String;
begin
  s:=Copy(Request.Authorization,7,length(Request.Authorization)-6);
  s:=TNetEncoding.Base64.Decode(s);
  if (Username='JohnDoe') and (Password='MyPassword') then
  begin
    if (Request.InternalPathInfo='') or (Request.InternalPathInfo='/') then Response.Content:=ReverseString.Content
    else if (Request.InternalPathInfo='ShowContent') or (Request.InternalPathInfo='/ShowContent') then Response.Content:=PP_ShowContent.Content
    else Response.SendRedirect(Request.InternalScriptName + '/');

    handled:=true;
  end
  else
  begin
    Response.Content:='Unauthorized';
    handled:=false;
  end;
end;

The user-check is static just for now, as the authorization is meant to be presented as a proof of concept.

However, if I do Authorization like this then I expect this function will grow way too big someday and I also miss out on ServerRoles. Unfortunately I am not versed enough in the topic of REST development to know what the proper way to do anything is.

I have seen that there is also an Authentication Manager that has been added by the Wizard. But as before I don't know what to do with it.


Solution

  • Try to use the component TDSAuthenticationManager connected with your TDSServer. The component TDSAuthenticationManager has a event called AuthenticationManager that is called before create user session. If your variable "valid" is true in the end, the user will authenticate.

    See this https://edn.embarcadero.com/br/article/41267 and this https://www.embarcadero.com/images/dm/technical-papers/rest-servers-in-delphi-xe-using-datasnap.pdf