无需第三方工具实现Angular应用间的单点登录(SSO)
Got it, let's work through how to implement single sign-on (SSO) between your Angular 1 (PO) and Angular 5 (XPP) apps without relying on third-party tools like Auth0. Your setup has specific constraints—PO is the only app with database access, uses OWIN without Identity, and handles registrations—so here's a tailored approach:
Since both apps interact with ASP.NET Web APIs and PO controls user data, we’ll make PO the central authentication authority. XPP will delegate all login/validation checks to PO, while both apps share a standardized identity token to recognize logged-in users.
1. Standardize Identity Tokens with JWT
First, update PO’s OWIN pipeline to generate JSON Web Tokens (JWT) for authenticated users. JWT is ideal here because it’s self-contained, portable, and easy to validate across apps:
- Include critical user data in the token (user ID, username, permissions) and sign it with a secret key stored securely on PO’s server (e.g., in
Web.config). - When users log into PO successfully, return the JWT to the Angular 1 frontend. PO can still keep its existing OWIN cookie for backward compatibility, but the JWT will be the shared token for SSO.
- Store the JWT in either:
- A root-domain cookie (e.g.,
.yourdomain.com) if both apps are on subdomains (po.yourdomain.com, xpp.yourdomain.com)—this lets both apps automatically access the token. localStorage/sessionStorageif apps are on separate domains (we’ll handle cross-domain transfer next).
- A root-domain cookie (e.g.,
2. Cross-App Token Sharing
For Same-Domain Apps
If PO and XPP share a root domain, the root-domain cookie will handle token sharing automatically. Both Angular frontends can read the cookie and attach the JWT to API requests via the Authorization: Bearer {token} header.
For Cross-Domain Apps
If apps are on separate domains, implement a redirect-based flow:
- When a user visits XPP without a valid token, redirect them to PO’s login page (with a
redirect_uriparameter pointing back to XPP). - If the user is already logged into PO, PO generates a JWT and redirects back to XPP’s callback endpoint, passing the token as a query parameter (always use HTTPS to avoid exposure).
- XPP’s Angular 5 frontend captures the token, stores it locally, and updates the UI to reflect logged-in state.
3. Unified Token Validation in Web APIs
Both PO and XPP’s Web APIs need to validate JWTs to authenticate requests:
- PO’s API: Keep existing OWIN cookie authentication, but add JWT validation middleware to support requests from XPP.
- XPP’s API: Add JWT validation middleware that uses PO’s secret key to verify token signatures, expiration, and issuer (PO’s domain). If validation fails, return a 401 error and redirect users to PO’s login.
Here’s a quick C# example of JWT validation setup in Startup.cs:
public void ConfigureAuth(IAppBuilder app) { var secretKey = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["JwtSecretKey"]); // Add JWT validation for cross-app requests app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(secretKey), ValidateIssuer = true, ValidIssuer = "https://po.yourdomain.com", // PO's domain as token issuer ValidateAudience = true, ValidAudience = "https://xpp.yourdomain.com", // Allow XPP as a valid audience ValidateLifetime = true, ClockSkew = TimeSpan.Zero // Strict expiration check } }); // Keep existing OWIN cookie auth for PO's native users app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); }
4. Sync Login/Logout States Across Apps
- Login Sync: When a user logs into PO, use
window.postMessageto send a notification to any open XPP tabs. XPP can then fetch the JWT from the shared cookie or redirect to PO’s callback to get the token. - Logout Sync: When a user logs out of PO, clear the shared JWT cookie and send a
postMessageto XPP to clear its local token and redirect to the login page.
5. Handle Registration Flow
Since only PO can handle registrations:
- XPP’s "Register" button should redirect users directly to PO’s registration page.
- After successful registration, PO automatically logs the user in, generates a JWT, and redirects back to XPP with the token (using the same redirect flow as login).
Key Security Notes
- Always use HTTPS to prevent token interception during transmission.
- Set a reasonable expiration time for JWTs, and implement a refresh token flow: when a token is about to expire, the frontend calls PO’s API to get a new token without re-authenticating.
- Never expose the JWT secret key to frontend code—keep it server-side only.
- XPP’s API should never access the user database directly; all user data requests should proxy through PO’s API to maintain data integrity.
内容的提问来源于stack exchange,提问作者M N Khan

