java如何实现单点登录
单点登录(SSO)的基本概念
单点登录是一种用户认证机制,允许用户通过一次登录访问多个相互信任的应用系统。核心原理是通过共享认证状态(如Token或Cookie)实现跨系统身份验证。
基于Token的SSO实现方案
1. 认证中心(Auth Server)
- 用户首次登录时,认证中心验证身份并生成Token(如JWT)。
- Token包含用户信息、有效期及签名(防篡改)。
- 示例JWT生成代码:
String token = JWT.create() .withSubject("user123") .withExpiresAt(new Date(System.currentTimeMillis() + 3600_000)) .sign(Algorithm.HMAC256("secret"));
2. 应用系统(Client)
- 应用系统拦截未认证请求,重定向到认证中心。
- 认证中心验证Token有效性后返回用户信息。
- 示例Token验证代码:
JWTVerifier verifier = JWT.require(Algorithm.HMAC256("secret")).build(); DecodedJWT decoded = verifier.verify(token); String userId = decoded.getSubject();
基于Cookie的SSO实现方案
1. 共享Cookie域
- 设置Cookie的Domain为父级域名(如
.example.com),子域名可共享。 - 示例设置Cookie代码:
Cookie cookie = new Cookie("sso_token", token); cookie.setDomain(".example.com"); cookie.setPath("/"); response.addCookie(cookie);
2. 跨域认证
- 若域名不同,通过认证中心中转(如OAuth 2.0)。
- 用户访问应用A时,跳转至认证中心获取授权码,再交换Token。
使用Spring Security + OAuth2实现SSO
1. 认证中心配置
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client1")
.secret("secret1")
.authorizedGrantTypes("authorization_code", "refresh_token")
.redirectUris("http://app1.com/login/oauth2/code/sso");
}
}
2. 资源服务器配置
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
}
}
3. 客户端集成
在application.properties中配置:
spring.security.oauth2.client.registration.sso.client-id=client1
spring.security.oauth2.client.registration.sso.client-secret=secret1
spring.security.oauth2.client.registration.sso.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.sso.redirect-uri=http://app1.com/login/oauth2/code/sso
spring.security.oauth2.client.provider.sso.issuer-uri=http://auth-server.com
安全注意事项
- Token有效期:设置较短的过期时间,结合Refresh Token机制。
- HTTPS:强制使用HTTPS传输Token/Cookie,防止中间人攻击。
- 签名验证:JWT必须验证签名,避免伪造Token。
以上方案可根据实际需求选择,Token方案适合前后端分离,Cookie方案适合传统Web应用,OAuth2适合复杂跨域场景。







