授权服务器(Authorization Server)目前并没有集成在Spring Security项目中,而是作为独立项目存在于Spring生态中,图1为Spring Authorization Server 在Spring 项目列表中的位置。
Spring Authorization Server 为什么没被集成在Spring Security中呢?
起因是因为Spring 中的Spring Security OAuth、Spring Cloud Security都对OAuth有自己的实现,Spring团队开始是想把OAuth独立出来放到Spring Security中,但是后面Spring团队意识到OAuth授权服务并不适合包含在Spring Security框架中,于是在2019年11月Spring宣布不在Spring Security中支持授权服务器。
但是对于Spring Security不再支持授权服务器,社区反应强烈。于是在2020年4月,Spring推出了Spring Authorization Server项目。
目前项目最新GA版本为0.3 GA,预览版本1.0.0-M1。
1、新创建一个Spring Boot项目,命名为 spring-security-authorization-server
2、引入pom依赖
- <pre class="prettyprint hljs xml" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;"><dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-security</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.security</groupId>
- <artifactId>spring-security-oauth2-authorization-server</artifactId>
- <version>0.3.1</version>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
class="prettyprint hljs livescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">import com.nimbusds.jose.jwk.JWKSet;
- import com.nimbusds.jose.jwk.RSAKey;
- import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
- import com.nimbusds.jose.jwk.source.JWKSource;
- import com.nimbusds.jose.proc.SecurityContext;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.core.Ordered;
- import org.springframework.core.annotation.Order;
- import org.springframework.security.config.Customizer;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer;
- import org.springframework.security.core.userdetails.User;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.core.userdetails.UserDetailsService;
- import org.springframework.security.crypto.factory.PasswordEncoderFactories;
- import org.springframework.security.oauth2.core.AuthorizationGrantType;
- import org