Orientação gerada a partir de informações públicas. Apenas para referência.
Um pacote Flutter/Dart para implementar clientes OpenID Connect, permitindo autenticação segura com provedores de identidade. Ele suporta fluxos OAuth 2.0, gerenciamento de tokens e descoberta de configurações do provedor por meio de pontos finais bem conhecidos. A biblioteca simplifica a integração com serviços como Google, Auth0 ou provedores de identidade personalizados, lidando com fluxos de autenticação complexos, incluindo o fluxo de código de autorização com PKCE. Projetado para uso em múltiplas plataformas, funciona perfeitamente em Android, iOS, Web, macOS, Windows e Linux. Ideal para aplicativos que exigem autenticação de usuário padronizada e segura.
Casos de uso
Integração com provedores de identidade OpenID Connect
Implementando fluxos de login seguros em aplicativos móveis e web
Gerenciando tokens e sessões do OAuth 2.0
Apoiar cenários de login único (SSO)
Construindo aplicativos autenticados do Flutter com provedores de identidade externos
Principais recursos
Suporta fluxos de OpenID Connect e OAuth 2.0
Descoberta automática da configuração do provedor
Suporte a PKCE para segurança aprimorada
Compatibilidade multiplataforma
Armazenamento de token e tratamento de atualização
API e exemplos bem documentados
Indicado para
Desenvolvedores criando aplicativos seguros do Flutter com autenticação externa
Equipes usando provedores de OpenID Connect
Aplicativos que exigem SSO ou identidade federada
Projetos que precisam de gerenciamento robusto do ciclo de vida do token
Considerações
Requer conhecimento dos conceitos do OpenID Connect
Necessita de configuração adequada das configurações do provedor de identidade
Pode exigir configuração adicional para domínios personalizados ou escopos
Não adequado para autenticação do lado do servidor diretamente
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
Library for working with OpenID Connect and implementing clients.
It currently supports these features:
discover OpenID Provider metadata
parsing and validating id tokens
basic tools for implementing implicit and authorization code flow
authentication for command line tools
RP initiated logout
Besides authentication providers that support OpenID Connect, this
library can also work with other authentication providers supporting
oauth2, like Facebook. For these providers, some features (e.g. discovery and id tokens)
will not work. You should define the metadata for those providers manually, except
for Facebook, which is predefined in the library.
Usage
Below are some examples of how to use the library. For more examples, see the example folder. It contains full examples of how to use the library with a keycloak server in a flutter, command line and browser application.
A simple usage example:
import'package:openid_client/openid_client.dart';
main() async {
// print a list of known issuersprint(Issuer.knownIssuers);
// discover the metadata of the google OPvar issuer = awaitIssuer.discover(Issuer.google);
// create a clientvar client = newClient(issuer, "client_id", "client_secret");
// create a credential object from authorization codevar c = client.createCredential(code: "some received authorization code");
// or from an access token
c = client.createCredential(accessToken: "some received access token");
// or from an id token
c = client.createCredential(idToken: "some id token");
// get userinfovar info = await c.getUserInfo();
print(info.name);
// get claims from id token if presentprint(c.idToken?.claims?.name);
// create an implicit authentication flowvar f = newFlow.implicit(client);
// or an explicit flow
f = newFlow.authorizationCode(client);
// set the redirect uri
f.redirectUri = Uri.parse("http://localhost");
// do something with the authentication urlprint(f.authenticationUrl);
// handle the result and get a credential object
c = await f.callback({
"code": "some code",
});
// validate an id tokenvar violations = await c.validateToken();
}
Usage example on flutter
// import the io versionimport'package:openid_client/openid_client_io.dart';
// use url launcher package import'package:url_launcher/url_launcher.dart';
authenticate(Uri uri, String clientId, List<String> scopes) async {
// create the clientvar issuer = awaitIssuer.discover(uri);
var client = newClient(issuer, clientId);
// create a function to open a browser with an urlurlLauncher(String url) async {
if (awaitcanLaunch(url)) {
awaitlaunch(url, forceWebView: true);
} else {
throw'Could not launch $url';
}
}
// create an authenticatorvar authenticator = newAuthenticator(client,
scopes: scopes,
port: 4000, urlLancher: urlLauncher);
// starts the authenticationvar c = await authenticator.authorize();
// close the webview when finishedcloseWebView();
// return the user inforeturnawait c.getUserInfo();
}
Usage example on command line
// import the io versionimport'package:openid_client/openid_client_io.dart';
authenticate(Uri uri, String clientId, List<String> scopes) async {
// create the clientvar issuer = awaitIssuer.discover(uri);
var client = newClient(issuer, clientId);
// create an authenticatorvar authenticator = newAuthenticator(client,
scopes: scopes,
port: 4000);
// starts the authenticationvar c = await authenticator.authorize(); // this will open a browser// return the user inforeturnawait c.getUserInfo();
}
Usage example in browser
// import the browser versionimport'package:openid_client/openid_client_browser.dart';
authenticate(Uri uri, String clientId, List<String> scopes) async {
// create the clientvar issuer = awaitIssuer.discover(uri);
var client = newClient(issuer, clientId);
// create an authenticatorvar authenticator = newAuthenticator(client, scopes: scopes);
// get the credentialvar c = await authenticator.credential;
if (c==null) {
// starts the authentication
authenticator.authorize(); // this will redirect the browser
} else {
// return the user inforeturnawait c.getUserInfo();
}
}
Please file feature requests and bugs at the issue tracker.
Sponsor
Creating and maintaining this package takes a lot of time. If you like the result, please consider to :heart: sponsor.
With your support, I will be able to further improve and support this project.
Also, check out my other dart packages at pub.dev.