SpringSecurity + Oauth2 + jwt实现单点登录
以下是一个使用Spring Security和OAuth2以及JWT实现单点登录的简化示例:
- 依赖管理(pom.xml):
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Security OAuth2 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
- Security配置(SecurityConfig.java):
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
}
- JWT的TokenProvider(TokenProvider.java):
@Component
public class TokenProvider {
private final String secretKey = "my_secret";
public String createToken(Authentication authentication) {
return Jwts.builder()
.setSubject(authentication.getName())
.signWith(Keys.hmacShaKeyFor(secretKey.getBytes()), SignatureAlgorithm.HS512)
.compact();
}
public boolean validateToken(String token) {
try {
Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(secretKey.getBytes()))
.build()
.parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
throw new InvalidTokenException("Token invalid or expired");
}
}
}
- 用户登录成功后的回调(OAuth2LoginSuccessHandler.java):
@Component
public class OAuth2LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Autowired
private TokenProvider tokenProvider;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, Servlet
评论已关闭