SSO客户端设计
下面通过模块merchant-security对 SSO客户端安全认证部分的实现进行封装,以便各个接入SSO的客户端应用进行引用。
安全认证的项目管理配置
SSO客户端安全认证的项目管理使用了如下所示的依赖配置:
<dependencies>
<dependency>
<groupId>com.demo</groupId>
<artifactId>merchant-client</artifactId><version>${project.version)</version></dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId></dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId></dependency>
</dependencies>
这个配置除主要引用Spring Cloud OAuth 2组件实现应用的安全管理和认证功能外,还引用了merchant-client模块以提供调用商家服务接口的功能,引用了Spring Boot Redis组件以提供使用缓存的功能。
安全认证项目的配置类
在SSO的客户端中启用Spring Security的认证功能,主要是通过一个配置类实现的。如下代码所示,我们创建一个配置类SecurityConfiguration,它继承于
WebSecurityConfigurerAdapter:
@Configuration
@EnableOAuth2Sso
@EnableConfigurationProperties (SecuritySettings.class)
public class SecurityConfiguration extends webSecurityConfigurerAdapter{
@Autowired
private AuthenticationManager authenticationManager;@Autowired
private SecuritySettings settings;
@Autowired
private RoleRestService roleRestService;@Autowired
private RedisCache redisCache;
@Bean(name = BeanIds.AUTHENT ICATION MANAGER)Goverride
public AuthenticationManager authenticationManagerBean() throws Excepti
return super.authenticationManagerBean();
)
@override
public void configure(HttpSecurity http) throws Exception
http.antMatcher("/**")
.authorizeRequests()
.antMatchers( "/login**").permitAll()
.antMatchers(settings.getPermitall()). permitAll()
.anyRequest()
.authenticated()
.and ().csrf().requireCsrfProtectionMatcher (csrfSecurityRequest
Matcher())
.csrfTokenRepository (csrfTokenRepository()) .and()
.addFilterAfter (csrfHeaderFilter(),CsrfFilter.class).logout()
.logoutUrl("/logout").permitAll()
.logoutSuccessUrl(settings.getLogoutsuccssurl()).and()
.exceptionHandling().accessDeniedPage (settings.getDeniedpage();
}
@Bean
public CustomFilterSecurityInterceptor customFilter() throws Exception t
CustomFilterSecurityInterceptor customFilter = new
CustomFilterSecurityInterceptor();
customFilter.setSecurityMetadataSource (securityMetadataSource());customFilter.setAccessDecisionManager(accessDecisionManager());
customFilter.setAuthenticationManager(a