java 实现SSO 示例代码
时间: 2024-01-22 21:03:29 浏览: 73
java sso实例
4星 · 用户满意度95%
以下是Java实现SSO单点登录的示例代码。
SSO服务器端代码:
```java
@Configuration
@EnableWebSecurity
public class SsoServerConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}
}
```
SSO客户端代码:
```java
@Configuration
@EnableWebSecurity
public class SsoClientConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SsoUserDetailsService ssoUserDetailsService;
@Autowired
private SsoLogoutSuccessHandler ssoLogoutSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessHandler(ssoLogoutSuccessHandler)
.deleteCookies("JSESSIONID")
.and()
.rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(ssoUserDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
以上代码仅供参考,实际使用时还需要根据自己的需求进行修改和完善。
阅读全文