SSO单点登录实现方式有多种,在这里不介绍理论,本文只讨论采用spring-security-oauth2来实现,本文共有三个服务,一个权限认证中心,两个客户端
org.springframework.boot spring-boot-starter-web
org.springframework.security.oauth spring-security-oauth2 2.3.8.RELEASE
server:port: 8830servlet:context-path: /auth
spring:application:name: cloud-oss-authorization-server
@EnableResourceServer
@SpringBootApplication
public class OssAuthorizationServerApplication {public static void main(String[] args) {SpringApplication.run(OssAuthorizationServerApplication.class, args);}
}
可以将Authorization Server和Resource Server放在同一个服务里
@Order(1)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("123456")).roles("USER");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.requestMatchers().antMatchers("/login", "/oauth/authorize").and().authorizeRequests().anyRequest().authenticated().and().formLogin().permitAll().and().csrf().disable();}@Beanpublic BCryptPasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate BCryptPasswordEncoder passwordEncoder;@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("SampleClientId").secret(passwordEncoder.encode("secret")).authorizedGrantTypes("authorization_code").scopes("user_info").autoApprove(true).redirectUris("http://localhost:8831/ui1/login", "http://localhost:8832/ui2/login");}
}
@RestController
public class UserController {@RequestMapping(value = "/user/me")public Principal user(Principal principal) {System.out.println(principal);return principal;}
}
分别新建两个客户端微服务8831和8832
org.springframework.boot spring-boot-starter-web
org.springframework.boot spring-boot-starter-security
org.springframework.security.oauth.boot spring-security-oauth2-autoconfigure
org.springframework.boot spring-boot-starter-thymeleaf
org.thymeleaf.extras thymeleaf-extras-springsecurity5
server:port: 8831 #另一个服务端口8832servlet:context-path: /ui1 #另一个服务路径/ui2register-default-servlet: truesession:cookie:name: UISESSION1 #另一个服务cookie nameUISESSION2
spring:application:name: cloud-sso-client8831 #另一个服务名称cloud-sso-client8832thymeleaf:cache: false
security:basic:enabled: falseoauth2:client:client-id: SampleClientIdclient-secret: secretaccess-token-uri: http://localhost:8830/auth/oauth/tokenuser-authorization-uri: http://localhost:8830/auth/oauth/authorizeresource:user-info-uri: http://localhost:8830/auth/user/me
@SpringBootApplication
public class OssClientApplication extends SpringBootServletInitializer {@Beanpublic RequestContextListener requestContextListener() {return new RequestContextListener();}public static void main(String[] args) {SpringApplication.run(OssClientApplication.class, args);}
}
@Configuration
@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login/**").permitAll().anyRequest().authenticated();}
}
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {@Beanpublic static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {return new PropertySourcesPlaceholderConfigurer();}@Overridepublic void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {configurer.enable();}@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("forward:/index");registry.addViewController("/index");registry.addViewController("/securedPage");}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");}
}
Spring Security SSO Client 1
Spring Security SSO Client 1
Login
Spring Security SSO
Secured Page
Welcome, Name
依次启动三个微服务cloud-oss-authorization-server、cloud-sso-client8831和cloud-sso-client8832
浏览器地址栏输入http://localhost:8831/ui1/

点击Login进入单点登录页

输入用户名和密码admin/123456
