The web: the server logs in
A browser has no safe place for tokens: memory, localStorage and IndexedDB are readable by any script that gets into the page. So in a browser the app's own server logs the user in, as Spring Security does for any web page: oauth2Login() of spring_boot_starter_security runs the authorization code flow as a confidential client, holds the tokens in its session, and gives the browser only an HttpOnly session cookie. This is the backend-for-frontend pattern, the strongest choice for a web app, and the default (spring.flutter.security.web.mode=server).
Why
The app's code stays the same as on phones: login('keycloak'), restore(), logout(), PrincipalBuilder, the Feign clients. No kIsWeb, no provider in the code. The registration ids are the server's, and the app has no registration of its own on the web.
Example
# lib/resources/application-web.yml
spring:
flutter:
security:
web:
mode: server # the default
server-url: https://api.neon.books # leave it out when the page and the API share an origin
user-endpoint: /api/me
logout-url: /api/logout
The server's "who is logged in" endpoint (spring_boot_starter_security):
// GET /user on the server, with the session cookie.
@RestController()
class UserController {
@GetMapping('/user')
Map<String, Object?> user(Authentication authentication) => {
'name': authentication.name,
'authorities': [
for (final authority in authentication.authorities) authority.authority,
],
if (authentication is OAuth2AuthenticationToken) ...{
'registrationId': authentication.authorizedClientRegistrationId,
'attributes': authentication.principal.attributes,
},
};
}
The properties
| Key | Type | Default | Meaning |
|---|---|---|---|
spring.flutter.security.web.mode |
server, spa |
server |
server: the app's server logs in. spa: the browser logs in by itself (see Spa mode) |
spring.flutter.security.web.server-url |
absolute http(s) URL, no query |
the page's origin | The app's server, with its context path if any. On another origin, requests to it carry the cookies, and the server must allow it (CORS with credentials) |
spring.flutter.security.web.user-endpoint |
path or absolute URL | /user |
GET with the session cookie: who is logged in |
spring.flutter.security.web.logout-url |
path or absolute URL | /logout |
POST with the CSRF token |
spring.flutter.security.web.authorization-base-uri |
path or absolute URL | /oauth2/authorization |
Where the server starts a login, followed by /{registrationId} (Spring's authorizationEndpoint().baseUri()) |
The keys are read in a browser only (the web platform profile); put them in application-web.yml. An invalid value stops the app at startup with the key's name.
How it works
ServerOAuth2LoginService is the OAuth2LoginService bean in a browser:
login('keycloak')navigates the page to<server-url>/oauth2/authorization/keycloakand returnsnull. The server sends the browser on to the provider and, after the login, back to the app (itsdefaultSuccessUrl, from the server's configuration, never from a request parameter). The app starts again.restore(), at startup, asks the user endpoint with the session cookie and puts the user into theSecurityContextHolder(soPrincipalNotifier,PrincipalBuilderand@PreAuthorizesee it), and publishes anAuthenticationSuccessEvent. Nobody logged in (401,403,204, a redirect to a login page):null. The server unreachable or answering something else: a warning,null.logout()posts the logout URL with the CSRF token, clears the context and publishes aLogoutSuccessEvent. When the server answers with the provider's logout page, the page goes there, the provider ends its session and sends the browser back.
The user endpoint
Spring has no standard "who am I" endpoint, so the server declares one (above). Its answer:
{
"name": "ada",
"authorities": ["ROLE_USER", "OIDC_USER", "SCOPE_profile"],
"registrationId": "keycloak",
"attributes": {"email": "[email protected]"}
}
nameis required;authorities(strings, or{"authority": "..."}objects as Jackson writes a SpringGrantedAuthority),registrationIdandattributesare optional; other members are ignored.- With
registrationIdthe user is anOAuth2AuthenticationToken; without one (a form login of the server) aPreAuthenticatedAuthenticationToken. The principal is anOAuth2Userwith the attributes either way. - The authorities are the server's, used as they are (no
GrantedAuthoritiesMapperin the browser).
The package offers no such controller: which user data a server shows its pages is the server's decision.
The logout answer
The app logs out with a script request (fetch), which cannot follow a redirect to the provider (another origin). So the server's logout success handler answers the provider's logout URL in one of two ways, and the page goes there:
200with{"logoutUrl": "https://id.neon.books/...logout?..."};- a
2xxwith aLocationheader, such as202 Accepted(exposeLocationin the CORS configuration for a server on another origin).
Any other success (204, a redirect) ends the server's session only. Only http and https URLs are followed. A 403 means the CSRF token was missing; the app logs out locally all the same.
Cookies and the CSRF token
In a browser the package declares the httpTransport bean: the browser's fetch, wrapped in CsrfCookieHttpTransport, which copies the server's XSRF-TOKEN cookie into the X-XSRF-TOKEN header of POST, PUT, PATCH and DELETE requests to that server, never to another origin. With the server on another origin, ServerCredentialsHttpTransport sends the cookies only to the server's origin, so a public API answering Access-Control-Allow-Origin: * keeps working and never sees the user's cookies. An app that declares its own HttpTransport keeps it, and builds the same with ServerCredentialsHttpTransport.forPage(page: page, server: server) wrapped in CsrfCookieHttpTransport.
The server's side
With spring_boot_starter_security:
oauth2Login()withdefaultSuccessUrl('<the web app>', alwaysUse: true);- CSRF tokens in a cookie the page may read:
CookieCsrfTokenRepository.withHttpOnlyFalse()withCsrfTokenRequestAttributeHandler, and a filter that writes the cookie on every response; - for a server on another origin: CORS for the page's origin with
allowCredentials: true(never*) andX-XSRF-TOKENamong the allowed headers; the page and the server on one site (app.neon.booksandapi.neon.books), because browsers drop third-party cookies; - the user endpoint and the logout answer above.
In development, the dev server's proxy puts the page and the API on one origin: forward /api/ with spring.flutter.web.dev-server.proxy (see The web).
What it protects, and what not
The tokens never reach the browser: a script injected into the page cannot steal them. The session cookie is HttpOnly; the CSRF token stops other sites from making the browser send requests with it. An injected script can still act as the user while the page is open. Flutter draws on a canvas and never turns data into HTML, so the classic DOM injection is mostly gone, but foreign scripts in index.html (analytics, tag managers), the supply chain, HtmlElementView with user HTML and other content on the same origin remain: keep them out, and send a Content Security Policy.
In Spring (Java)
This mode is oauth2Login() itself. Spring has no client side for it: it leaves the page's side to the page (Angular reads the XSRF-TOKEN cookie by itself; a "who am I" endpoint is the application's).