Add to your Cargo.toml
:
toml
yew-oauth2 = "0.6"
By default, the router
integration is disabled, you can enable it using:
toml
yew-oauth2 = { version = "0.6", features = ["router"] }
OpenID Connect requires an additional dependency and can be enabled using the feature openid
.
A quick example how to use it (see below for more complete examples):
``rust
use yew::prelude::*;
use yew_oauth2::prelude::*;
use yew_oauth2::oauth2::*; // use
openid::*` when using OpenID connect
fn myapp() -> Html { let config = Config { clientid: "my-client".into(), authurl: "https://my-sso/auth/realms/my-realm/protocol/openid-connect/auth".into(), tokenurl: "https://my-sso/auth/realms/my-realm/protocol/openid-connect/token".into(), };
html!(
fn myappmain() -> Html { let agent = useauthagent().expect("Must be nested inside an OAuth2 component");
let login = { let agent = agent.clone(); Callback::from(move || { let _ = agent.startlogin(); }) }; let logout = Callback::from(move |_| { let _ = agent.logout(); });
html!(
<>
This repository also has some complete examples:
Testing the example projects locally can be done using a local Keycloak instance and trunk
.
Start the Keycloak instance using:
shell
podman-compose -f develop/docker-compose.yaml up
Then start trunk
with the local developer instance:
shell
cd yew-oauth2-example # or yew-oauth2-redirect-example
trunk serve
And navigate your browser to http://localhost:8080.
NOTE: It is important to use http://localhost:8080
instead of e.g. http://127.0.0.1:8080
, as Keycloak is
configured by default to use http://localhost:*
as a valid redirect URL when in dev-mode. Otherwise, you will get
an "invalid redirect" error from Keycloak.