使用SpringSecurity体验OAUTH2之一 (入门1)
OAUTH2是一种安全的授权框架,其原理在网上有许多文章上可以看到。但从实践角度,好的文章比较少。SpringSecurity框架本身是支持OAUTH2的,所以下面通过使用SpringSecurity框架做个DEMO,从代码级别体验下OAUTH2。
还是先创建一个SpringBoot的项目,然后添加相应的依赖(可以看出springCloud对oatuth2已经有了很好的支持)
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring-security-oauth2-autoconfigure.version>2.1.0.RELEASE</spring-security-oauth2-autoconfigure.version> </properties>
<dependencies> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>${spring-security-oauth2-autoconfigure.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> </dependencies>
添加启动类
@SpringBootApplication @EnableAuthorizationServer //这个注解也是根据Springcloud的惯例进行添加 public class AuthorizationApp { public static void main( String[] args ) { SpringApplication.run(AuthorizationApp.class, args) ; } }
至于application.yml文件暂时啥都没配,启动 AuthorizationApp 实例后,在8080默认端口启动了web服务,按着对OAUTH协议的理解,这样应该是启动了OAUTH2的authorizagion server。
下面先分析下,会加载哪些配置:
一. 由@EnableAuthorizationServer注解引出的配置
查看@EnableAuthorizationServer注解源码,如下:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({AuthorizationServerEndpointsConfiguration.class, AuthorizationServerSecurityConfiguration.class}) public @interface EnableAuthorizationServer { }
可以看到其导入了两个配置类 :AuthorizationServerEndpointsConfiguration , AuthorizationServerSecurityConfiguration
根据@EnableAuthorizationServer的注释可知,这个authorization server暴露出两个http endpoint给我们调用,分别是 /oauth/authorize (实现类AuthorizationEndpoint)和 /oauth/token (实现类TokenEndpoint)
二. 自动配置类 OAuth2AutoConfiguration
这是由 依赖的spring-security-oauth2-autoconfigure导入的,OAuth2AutoConfiguration的源码
@Configuration @ConditionalOnClass({ OAuth2AccessToken.class, WebMvcConfigurer.class }) @Import({ OAuth2AuthorizationServerConfiguration.class, OAuth2MethodSecurityConfiguration.class, OAuth2ResourceServerConfiguration.class, OAuth2RestOperationsConfiguration.class }) @AutoConfigureBefore(WebMvcAutoConfiguration.class) @EnableConfigurationProperties(OAuth2ClientProperties.class) public class OAuth2AutoConfiguration { private final OAuth2ClientProperties credentials; public OAuth2AutoConfiguration(OAuth2ClientProperties credentials) { this.credentials = credentials; } @Bean public ResourceServerProperties resourceServerProperties() { return new ResourceServerProperties(this.credentials.getClientId(), this.credentials.getClientSecret()); } }
由源码可知,又引入了几个配置类:
OAuth2AuthorizationServerConfiguration.class,
OAuth2MethodSecurityConfiguration.class,
OAuth2ResourceServerConfiguration.class,
OAuth2RestOperationsConfiguration.class
从以上分析来看,似乎有两套配置参与了OAuth2的使用,究竟是哪一套在起作用,还是两套在合作着起作用呢,请看后续分析。