By Admin on Wednesday, 25 November 2020
Category: All

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.

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

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 ...

​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.

Related Posts