OAuth2 Server Authorization

From sgcWebSockets 4.4.5 OAuth2 protocol is supported on Server Components.

OAuth2 allows third-party applications to receive a limited access to an HTTP service which is either on behalf of a resource owner or by allowing a third-party application obtain access on its own behalf. Thanks to OAuth2, service providers and consumer applications can interact with each other in a secure way.

TsgcHTTP_OAuth2_Server

This component provides the OAuth2 protocol implementation in Server Side Components.

The server components have a property called Authorization.OAuth.OAuth2 where you can assign an instance of TsgcHTTP_OAuth2_Server, so if Authentication is enabled and OAuh2 property is attached to OAuth2 Server Component, the WebSocket and HTTP Requests require a Bearer Token to be processed, if not the connection will be closed automatically.

Sample Example 

Let's do a simple OAuth2 server example, using a TsgcWebSocketHTTPServer.

First, create a new TsgcWebSocketHTTPServer listening on port 443 and using a self-signed certificate in sgc.pem file.

oServer := TsgcWebSocketHTTPServer.Create(nil);
oServer.Port := 80;
oServer.SSLOptions.Port := 443;
oServer.SSLOptions.CertFile := 'sgc.pem';
oServer.SSLOptions.KeyFile := 'sgc.pem';
oServer.SSLOptions.RootCertFile := 'sgc.pem';
oServer.SSL := True; 

Then create a new instance of TsgcHTTP_OAuth2_Server and assign to previously created server.

Register a new Application with the following values:

Name: MyApp

RedirectURI: http://127.0.0.1:8080

ClientId: client-id

ClientSecret: client-secret

OAuth2 := TsgcHTTP_OAuth2_Server.Create(nil);
OAuth2.Apps.AddApp('MyApp', 'http://127.0.0.1:8080', 'client-id', 'client-secret');
oServer.Authentication.Enabled := True;
oServer.Authentication.OAuth.OAuth2 := OAuth2; 

Then handle OnOAuth2Authentication event of OAuth2 server component and implement your own method to login users. I will use the pair "user/secret" to accept a login.Enter your text here ...

procedure OnAuth2Authentication(Connection: TsgcWSConnection; OAuth2: TsgcHTTPOAuth2Request; aUser, aPassword: string; var Authenticated: Boolean);
begin
  if ((aUser = 'user') and (aPassword = 'secret')) then
    Authenticated := True;
end; 

Finally start the server and use a OAuth2 client to login, example you can use the TsgcHTTP_OAuth2_Client included with sgcWebSockets library.

Request a New Access Token, a new Web Browser session will be shown and user must Allow connection and then login.


If login is successful a new Token will be returned to the client. Then all the requests must include this bearer token in the HTTP Headers.

×
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

OAuth2 Server Endpoints
Worldpay WebSocket STOMP API

Related Posts