-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleAuthService.vb
More file actions
176 lines (144 loc) · 6.6 KB
/
GoogleAuthService.vb
File metadata and controls
176 lines (144 loc) · 6.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
Imports System.Net
Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Text.Json.Serialization
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports System.IO
''' <summary>
''' Clase completa para gestionar OAuth2 con Google.
''' </summary>
Public Class GoogleAuthService
' Configuración de la API
Private ReadOnly _clientId As String
Private ReadOnly _clientSecret As String
Private ReadOnly _scopes As String()
Private ReadOnly _redirectUri As String = "http://127.0.0.1:55555/"
' Endpoints de Google
Private Const AuthEndpoint As String = "https://accounts.google.com/o/oauth2/v2/auth"
Private Const TokenEndpoint As String = "https://oauth2.googleapis.com/token"
Public Sub New(clientId As String, clientSecret As String, scopes As String())
_clientId = clientId
_clientSecret = clientSecret
_scopes = scopes
End Sub
''' <summary>
''' Inicia el flujo de autenticación: abre el navegador, espera el código y obtiene los tokens.
''' </summary>
Public Async Function AuthenticateAsync() As Task(Of GoogleToken)
' 1. Crear el HttpListener para esperar la respuesta de Google
Using listener As New HttpListener()
listener.Prefixes.Add(_redirectUri)
listener.Start()
' 2. Generar URL de autorización
Dim scopeString = String.Join(" ", _scopes)
Dim authUrl = $"{AuthEndpoint}?response_type=code&client_id={_clientId}&redirect_uri={_redirectUri}&scope={Uri.EscapeDataString(scopeString)}&access_type=offline&prompt=consent"
' 3. Abrir el navegador predeterminado
OpenBrowser(authUrl)
' 4. Esperar a que llegue la petición al puerto local
Dim context = Await listener.GetContextAsync()
Dim request = context.Request
Dim response = context.Response
' 5. Extraer el código de la URL
Dim code = request.QueryString("code")
Dim errorString = request.QueryString("error")
' 6. Responder al navegador para cerrar la pestaña amigablemente
Dim responseString As String
If Not String.IsNullOrEmpty(code) Then
responseString = "<html><body><h1>Autenticacion exitosa!</h1><p>Puedes cerrar esta ventana y volver a la aplicacion.</p><script>window.close();</script></body></html>"
Else
responseString = $"<html><body><h1>Error: {errorString}</h1></body></html>"
End If
Dim buffer = Encoding.UTF8.GetBytes(responseString)
response.ContentLength64 = buffer.Length
Dim output = response.OutputStream
Await output.WriteAsync(buffer, 0, buffer.Length)
output.Close()
listener.Stop()
If String.IsNullOrEmpty(code) Then
Throw New Exception($"Error en autenticación: {errorString}")
End If
' 7. Intercambiar el código por el Token
Return Await ExchangeCodeForTokenAsync(code)
End Using
End Function
''' <summary>
''' Intercambia el código de autorización por un Access Token y Refresh Token.
''' </summary>
Private Async Function ExchangeCodeForTokenAsync(code As String) As Task(Of GoogleToken)
Using client As New HttpClient()
Dim params As New Dictionary(Of String, String) From {
{"code", code},
{"client_id", _clientId},
{"client_secret", _clientSecret},
{"redirect_uri", _redirectUri},
{"grant_type", "authorization_code"}
}
Dim content As New FormUrlEncodedContent(params)
Dim response = Await client.PostAsync(TokenEndpoint, content)
Dim jsonString = Await response.Content.ReadAsStringAsync()
If Not response.IsSuccessStatusCode Then
Throw New Exception($"Error obteniendo token: {jsonString}")
End If
Return JsonSerializer.Deserialize(Of GoogleToken)(jsonString)
End Using
End Function
''' <summary>
''' Usa el Refresh Token para obtener un nuevo Access Token cuando el anterior expira.
''' </summary>
Public Async Function RefreshTokenAsync(refreshToken As String) As Task(Of GoogleToken)
Using client As New HttpClient()
Dim params As New Dictionary(Of String, String) From {
{"client_id", _clientId},
{"client_secret", _clientSecret},
{"refresh_token", refreshToken},
{"grant_type", "refresh_token"}
}
Dim content As New FormUrlEncodedContent(params)
Dim response = Await client.PostAsync(TokenEndpoint, content)
Dim jsonString = Await response.Content.ReadAsStringAsync()
If Not response.IsSuccessStatusCode Then
Throw New Exception($"Error refrescando token: {jsonString}")
End If
Dim newToken = JsonSerializer.Deserialize(Of GoogleToken)(jsonString)
' La respuesta de refresh a veces no devuelve un nuevo refresh_token,
' así que mantenemos el viejo si el nuevo es nulo.
If String.IsNullOrEmpty(newToken.RefreshToken) Then
newToken.RefreshToken = refreshToken
End If
Return newToken
End Using
End Function
' Método auxiliar para abrir navegador compatible con .NET Core y Framework
Private Sub OpenBrowser(url As String)
Try
Process.Start(New ProcessStartInfo(url) With {.UseShellExecute = True})
Catch ex As Exception
' Fallback para algunos entornos de Windows
Process.Start("cmd", $"/c start {url.Replace("&", "^&")}")
End Try
End Sub
End Class
''' <summary>
''' Estructura de datos para mapear la respuesta JSON de Google.
''' </summary>
Public Class GoogleToken
<JsonPropertyName("access_token")>
Public Property AccessToken As String
<JsonPropertyName("expires_in")>
Public Property ExpiresIn As Integer
<JsonPropertyName("refresh_token")>
Public Property RefreshToken As String
<JsonPropertyName("scope")>
Public Property Scope As String
<JsonPropertyName("token_type")>
Public Property TokenType As String
Public ReadOnly Property CreatedDate As DateTime = DateTime.Now
' Propiedad auxiliar para saber si ha expirado (con margen de 1 minuto)
Public ReadOnly Property IsExpired As Boolean
Get
Return DateTime.Now >= CreatedDate.AddSeconds(ExpiresIn - 60)
End Get
End Property
End Class