delphimvcframework/sources/MVCFramework.Middleware.Authentication.pas

476 lines
15 KiB
ObjectPascal
Raw Normal View History

// ***************************************************************************
//
// Delphi MVC Framework
//
2024-01-02 17:04:27 +01:00
// Copyright (c) 2010-2024 Daniele Teti and the DMVCFramework Team
//
// https://github.com/danieleteti/delphimvcframework
//
// ***************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// *************************************************************************** }
2015-12-22 12:38:17 +01:00
2015-04-01 17:01:23 +02:00
unit MVCFramework.Middleware.Authentication;
{$I dmvcframework.inc}
interface
2015-04-01 17:01:23 +02:00
uses
System.SysUtils,
System.StrUtils,
System.Generics.Collections,
System.JSON,
MVCFramework,
MVCFramework.Commons,
MVCFramework.Serializer.Commons;
2015-04-01 17:01:23 +02:00
type
2015-04-01 17:01:23 +02:00
TMVCBasicAuthenticationMiddleware = class(TInterfacedObject, IMVCMiddleware)
private
FAuthenticationHandler: IMVCAuthenticationHandler;
2015-04-01 17:01:23 +02:00
FRealm: string;
protected
procedure OnBeforeRouting(
AContext: TWebContext;
var AHandled: Boolean
);
procedure OnBeforeControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName: string;
const AActionName: string;
var AHandled: Boolean
);
procedure OnAfterControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName: string; const AActionName: string;
const AHandled: Boolean
);
procedure OnAfterRouting(AContext: TWebContext; const AHandled: Boolean);
2015-04-01 17:01:23 +02:00
public
constructor Create(
const AAuthenticationHandler: IMVCAuthenticationHandler;
const ARealm: string = 'DelphiMVCFramework REALM'
); virtual;
2015-04-01 17:01:23 +02:00
end;
TMVCCustomAuthenticationMiddleware = class(TInterfacedObject, IMVCMiddleware)
private
FAuthenticationHandler: IMVCAuthenticationHandler;
FLoginUrl: string;
protected
procedure OnBeforeRouting(
AContext: TWebContext;
var AHandled: Boolean
);
procedure OnBeforeControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName: string;
const AActionName: string;
var AHandled: Boolean
); virtual;
procedure OnAfterControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName: string; const AActionName: string;
const AHandled: Boolean);
procedure OnAfterRouting(
AContext: TWebContext;
const AHandled: Boolean
);
procedure SendResponse(AContext: TWebContext; var AHandled: Boolean; AHttpStatus: Word = HTTP_STATUS.Unauthorized);
procedure DoLogin(AContext: TWebContext; var AHandled: Boolean);
procedure DoLogout(AContext: TWebContext; var AHandled: Boolean);
public
constructor Create(
const AAuthenticationHandler: IMVCAuthenticationHandler;
const ALoginUrl: string = '/system/users/logged'
); virtual;
end;
2015-04-01 17:01:23 +02:00
implementation
const
CONTENT_HTML_FORMAT = '<html><body><h1>%s</h1><p>%s</p></body></html>';
2015-04-01 17:01:23 +02:00
CONTENT_401_NOT_AUTHORIZED = '401: Not authorized';
CONTENT_403_FORBIDDEN = '403: Forbidden';
{ TMVCBasicAuthenticationMiddleware }
2015-04-01 17:01:23 +02:00
constructor TMVCBasicAuthenticationMiddleware.Create(
const AAuthenticationHandler: IMVCAuthenticationHandler;
const ARealm: string);
2015-04-01 17:01:23 +02:00
begin
inherited Create;
FAuthenticationHandler := AAuthenticationHandler;
FRealm := ARealm;
2015-04-01 17:01:23 +02:00
end;
procedure TMVCBasicAuthenticationMiddleware.OnAfterControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName: string; const AActionName: string;
const AHandled: Boolean
);
2015-04-01 17:01:23 +02:00
begin
// Implement as needed
2015-04-01 17:01:23 +02:00
end;
procedure TMVCBasicAuthenticationMiddleware.OnAfterRouting(AContext: TWebContext; const AHandled: Boolean);
begin
end;
procedure TMVCBasicAuthenticationMiddleware.OnBeforeControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName, AActionName: string;
var AHandled: Boolean);
2015-04-01 17:01:23 +02:00
procedure SendWWWAuthenticate;
begin
AContext.LoggedUser.Clear;
if AContext.Request.ClientPreferHTML then
2015-04-01 17:01:23 +02:00
begin
AContext.Response.ContentType := TMVCMediaType.TEXT_HTML;
AContext.Response.RawWebResponse.Content :=
Format(CONTENT_HTML_FORMAT, [CONTENT_401_NOT_AUTHORIZED, AContext.Config[TMVCConfigKey.ServerName]]);
2015-04-01 17:01:23 +02:00
end
else
begin
AContext.Response.ContentType := TMVCMediaType.TEXT_PLAIN;
AContext.Response.RawWebResponse.Content := CONTENT_401_NOT_AUTHORIZED + sLineBreak + AContext.Config
[TMVCConfigKey.ServerName];
2015-04-01 17:01:23 +02:00
end;
AContext.Response.StatusCode := HTTP_STATUS.Unauthorized;
AContext.Response.SetCustomHeader('WWW-Authenticate', 'Basic realm=' + QuotedStr(FRealm));
AContext.SessionStop(False);
AHandled := True;
2015-04-01 17:01:23 +02:00
end;
procedure Send403Forbidden;
begin
AContext.LoggedUser.Clear;
if AContext.Request.ClientPreferHTML then
2015-04-01 17:01:23 +02:00
begin
AContext.Response.ContentType := TMVCMediaType.TEXT_HTML;
AContext.Response.RawWebResponse.Content :=
Format(CONTENT_HTML_FORMAT, [CONTENT_403_FORBIDDEN, AContext.Config[TMVCConfigKey.ServerName]]);
end
else if AContext.Request.ContentMediaType.StartsWith(TMVCMediaType.APPLICATION_JSON) then
begin
AContext.Response.ContentType := TMVCMediaType.APPLICATION_JSON;
AContext.Response.RawWebResponse.Content :=
'{"status":"error", "message":"' + CONTENT_403_FORBIDDEN.Replace('"', '\"') + '"}';
2015-04-01 17:01:23 +02:00
end
else
begin
AContext.Response.ContentType := TMVCMediaType.TEXT_PLAIN;
AContext.Response.RawWebResponse.Content := CONTENT_403_FORBIDDEN + sLineBreak + AContext.Config
[TMVCConfigKey.ServerName];
2015-04-01 17:01:23 +02:00
end;
AContext.Response.StatusCode := HTTP_STATUS.Forbidden;
AContext.Response.ReasonString := AContext.Config[TMVCConfigKey.ServerName];
AHandled := True;
2015-04-01 17:01:23 +02:00
end;
var
AuthRequired: Boolean;
IsValid, IsAuthorized: Boolean;
AuthHeader, Token: string;
AuthPieces: TArray<string>;
RolesList: TList<string>;
SessionData: TSessionData;
SessionPair: TPair<string, string>;
2015-04-01 17:01:23 +02:00
begin
FAuthenticationHandler.OnRequest(AContext, AControllerQualifiedClassName, AActionName, AuthRequired);
if not AuthRequired then
2015-04-01 17:01:23 +02:00
begin
AHandled := False;
2015-04-01 17:01:23 +02:00
Exit;
end;
AContext.LoggedUser.LoadFromSession(AContext.Session);
IsValid := AContext.LoggedUser.IsValid;
if not IsValid then
2015-04-01 17:01:23 +02:00
begin
AuthHeader := AContext.Request.Headers['Authorization'];
if AuthHeader.IsEmpty or (not AuthHeader.StartsWith('Basic ', True)) then
begin
SendWWWAuthenticate;
Exit;
end;
Token := AuthHeader.Remove(0, 'Basic '.Length).Trim;
AuthHeader := TMVCSerializerHelper.DecodeString(Token);
AuthPieces := AuthHeader.Split([':']);
if Length(AuthPieces) <> 2 then
2015-04-01 17:01:23 +02:00
begin
SendWWWAuthenticate;
Exit;
end;
RolesList := TList<string>.Create;
2015-04-01 17:01:23 +02:00
try
SessionData := TSessionData.Create;
try
FAuthenticationHandler.OnAuthentication(AContext, AuthPieces[0], AuthPieces[1], RolesList, IsValid,
SessionData);
if IsValid then
begin
AContext.LoggedUser.Roles.AddRange(RolesList);
AContext.LoggedUser.UserName := AuthPieces[0];
AContext.LoggedUser.LoggedSince := Now;
AContext.LoggedUser.Realm := FRealm;
AContext.LoggedUser.SaveToSession(AContext.Session);
for SessionPair in SessionData do
AContext.Session[SessionPair.Key] := SessionPair.Value;
end;
finally
SessionData.Free;
2015-04-01 17:01:23 +02:00
end;
finally
RolesList.Free;
2015-04-01 17:01:23 +02:00
end;
end;
IsAuthorized := False;
if IsValid then
FAuthenticationHandler.OnAuthorization(AContext, AContext.LoggedUser.Roles, AControllerQualifiedClassName,
AActionName, IsAuthorized);
2015-04-01 17:01:23 +02:00
if IsAuthorized then
AHandled := False
2015-04-01 17:01:23 +02:00
else
begin
if IsValid then
2015-04-01 17:01:23 +02:00
Send403Forbidden
else
begin
2015-04-01 17:01:23 +02:00
SendWWWAuthenticate;
end;
2015-04-01 17:01:23 +02:00
end;
end;
procedure TMVCBasicAuthenticationMiddleware.OnBeforeRouting(
AContext: TWebContext;
var AHandled: Boolean);
2015-04-01 17:01:23 +02:00
begin
AHandled := False;
2015-04-01 17:01:23 +02:00
end;
{ TMVCCustomAuthenticationMiddleware }
constructor TMVCCustomAuthenticationMiddleware.Create(
const AAuthenticationHandler: IMVCAuthenticationHandler;
const ALoginUrl: string);
begin
inherited Create;
FAuthenticationHandler := AAuthenticationHandler;
FLoginUrl := ALoginUrl.ToLower;
end;
procedure TMVCCustomAuthenticationMiddleware.DoLogin(
AContext: TWebContext;
var AHandled: Boolean);
2016-09-18 19:19:23 +02:00
var
Jo: TJSONObject;
UserName, Password: string;
RolesList: TList<string>;
SessionPair: TPair<string, string>;
SessionData: TSessionData;
IsValid: Boolean;
2016-09-18 19:19:23 +02:00
begin
AContext.SessionStop(False);
AContext.LoggedUser.Clear;
if not AContext.Request.ThereIsRequestBody then
2016-09-18 19:19:23 +02:00
begin
AHandled := True;
AContext.Response.StatusCode := HTTP_STATUS.BadRequest;
AContext.Response.ContentType := TMVCMediaType.APPLICATION_JSON;
AContext.Response.RawWebResponse.Content :=
'{"status":"error", "message":"username and password are mandatory in the body request as json object"}';
2016-09-18 19:19:23 +02:00
Exit;
end;
Jo := TJSONObject.ParseJSONValue(AContext.Request.Body) as TJSONObject;
try
if not Assigned(Jo) then
begin
AHandled := True;
SendResponse(AContext, AHandled, HTTP_STATUS.BadRequest);
Exit;
end;
2016-09-18 19:19:23 +02:00
UserName := EmptyStr;
if (Jo.Get('username') <> nil) then
UserName := Jo.Get('username').JsonValue.Value;
2016-09-18 19:19:23 +02:00
Password := EmptyStr;
if (Jo.Get('password') <> nil) then
Password := Jo.Get('password').JsonValue.Value;
if UserName.IsEmpty or Password.IsEmpty then
begin
AHandled := True;
SendResponse(AContext, AHandled);
Exit;
end;
2016-09-18 19:19:23 +02:00
RolesList := TList<string>.Create;
2016-09-18 19:19:23 +02:00
try
SessionData := TSessionData.Create;
try
IsValid := False;
FAuthenticationHandler.OnAuthentication(AContext, UserName, Password, RolesList, IsValid, SessionData);
if not IsValid then
begin
SendResponse(AContext, AHandled);
Exit;
end;
2016-09-18 19:19:23 +02:00
AContext.LoggedUser.Roles.AddRange(RolesList);
AContext.LoggedUser.UserName := UserName;
AContext.LoggedUser.LoggedSince := Now;
AContext.LoggedUser.Realm := 'custom';
AContext.LoggedUser.SaveToSession(AContext.Session);
2016-09-18 19:19:23 +02:00
for SessionPair in SessionData do
AContext.Session[SessionPair.Key] := SessionPair.Value;
2016-09-18 19:19:23 +02:00
AContext.Response.StatusCode := HTTP_STATUS.OK;
AContext.Response.CustomHeaders.Values['X-LOGOUT-URL'] := FLoginUrl;
AContext.Response.CustomHeaders.Values['X-LOGOUT-METHOD'] := 'DELETE';
AContext.Response.ContentType := TMVCMediaType.APPLICATION_JSON;
AContext.Response.RawWebResponse.Content := '{"status":"OK"}';
AHandled := True;
finally
SessionData.Free;
end;
2016-09-18 19:19:23 +02:00
finally
RolesList.Free;
2016-09-18 19:19:23 +02:00
end;
finally
Jo.Free;
2016-09-18 19:19:23 +02:00
end;
end;
procedure TMVCCustomAuthenticationMiddleware.DoLogout(
AContext: TWebContext; var AHandled: Boolean);
2016-09-18 19:19:23 +02:00
begin
AContext.SessionStop(False);
SendResponse(AContext, AHandled, HTTP_STATUS.OK);
2016-09-18 19:19:23 +02:00
end;
procedure TMVCCustomAuthenticationMiddleware.OnAfterControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName: string; const AActionName: string;
const AHandled: Boolean);
begin
// Implement as needed
end;
procedure TMVCCustomAuthenticationMiddleware.OnAfterRouting(AContext: TWebContext; const AHandled: Boolean);
begin
end;
procedure TMVCCustomAuthenticationMiddleware.OnBeforeControllerAction(
AContext: TWebContext;
const AControllerQualifiedClassName, AActionName: string;
var AHandled: Boolean);
var
IsValid: Boolean;
IsAuthorized: Boolean;
AuthRequired: Boolean;
begin
FAuthenticationHandler.OnRequest(AContext, AControllerQualifiedClassName, AActionName, AuthRequired);
if not AuthRequired then
begin
AHandled := False;
Exit;
end;
AContext.LoggedUser.LoadFromSession(AContext.Session);
IsValid := AContext.LoggedUser.IsValid;
if not IsValid then
begin
AContext.SessionStop(False);
SendResponse(AContext, AHandled);
Exit;
end;
IsAuthorized := False;
FAuthenticationHandler.OnAuthorization(AContext, AContext.LoggedUser.Roles, AControllerQualifiedClassName,
AActionName, IsAuthorized);
if IsAuthorized then
AHandled := False
else
begin
if IsValid then
SendResponse(AContext, AHandled, HTTP_STATUS.Forbidden)
else
SendResponse(AContext, AHandled, HTTP_STATUS.Unauthorized);
end;
end;
procedure TMVCCustomAuthenticationMiddleware.OnBeforeRouting(
AContext: TWebContext; var AHandled: Boolean);
begin
if (AContext.Request.PathInfo.ToLower = FLoginUrl) then
begin
AHandled := False;
if (AContext.Request.HTTPMethod = httpPOST) and
(AContext.Request.ContentType.StartsWith(TMVCMediaType.APPLICATION_JSON)) then
DoLogin(AContext, AHandled);
if (AContext.Request.HTTPMethod = httpDELETE) then
DoLogout(AContext, AHandled);
end;
end;
procedure TMVCCustomAuthenticationMiddleware.SendResponse(
AContext: TWebContext; var AHandled: Boolean; AHttpStatus: Word);
var
IsPositive: Boolean;
Msg: string;
begin
AContext.LoggedUser.Clear;
AContext.Response.CustomHeaders.Values['X-LOGIN-URL'] := FLoginUrl;
AContext.Response.CustomHeaders.Values['X-LOGIN-METHOD'] := 'POST';
AContext.Response.StatusCode := AHttpStatus;
if AContext.Request.ClientPreferHTML then
begin
AContext.Response.ContentType := TMVCMediaType.TEXT_HTML;
AContext.Response.RawWebResponse.Content :=
Format(CONTENT_HTML_FORMAT, [IntToStr(AHttpStatus), AContext.Config[TMVCConfigKey.ServerName]]);
end
else
begin
IsPositive := (AHttpStatus div 100) = 2;
Msg := IfThen(IsPositive, 'OK', 'KO');
AContext.Response.ContentType := TMVCMediaType.APPLICATION_JSON;
AContext.Response.RawWebResponse.Content := '{"status":"' + Msg + '", "message":"' + IntToStr(AHttpStatus) + '"}';
end;
AHandled := True;
end;
2015-04-01 17:01:23 +02:00
end.