媒介
技术更新:Spring Security OAuth已经逐渐被镌汰,而Spring Authorization Server是其官方保举的替代方案。它提供了更现代、更安全的授权服务器实现,符合最新的OAuth 2.1规范。
项目需求:小灰工作上的项目需要搭建一个授权服务器,而原先使用的Spring Security OAuth,而该项目已经逐渐被镌汰,固然网上有许多相关教程和资料,但考虑到技术的更新迭代,决定采用Spring Authorization Server来实现。
功能实现:该项目包括认证授权中央、资源服务器、客户端和服务端。通过使用Spring Authorization Server,可以确保这些功能的安全性和可靠性,同时遵循最新的安全尺度。
项目功能
授权中央Server:进行认证、授权,并发放token、刷新token,不负责token鉴权(由资源服务器自行鉴权);
客户端Client:面向用户的操作入口;向Server哀求token,携带token访问Resource;
资源服务器Resource:提供资源,需要携带token哀求,可以自行鉴权;
项目布局
项目搭建
说明:项目相关架包、数据库脚本相关信息在项目里,具体可链接下载。
授权中央Server(spring-authorization-server):
application.yaml
- server:
- port: 9000
- servlet:
- session:
- cookie:
- name: OAuth-Auth-Server
- logging:
- level:
- root: info
- org.springframework.web: info
- org.springframework.security: trace
- org.springframework.security.oauth2: trace
- spring:
- thymeleaf:
- cache: false
- prefix: classpath:/templates
- # check-template-location: true
- suffix: .html
- mode: HTML
- datasource:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://ip:3306/oauth2.0?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
- username: root
- password: ********
复制代码 新建AuthorizationServer相关设置
- @Configuration
- @EnableWebSecurity
- public class AuthorizationServerConfig {
-
- @Autowired
- private PasswordEncoder passwordEncoder;
- /**
- * 授权服务器 SecurityFilterChain
- * @param http
- * @return
- * @throws Exception
- */
- @Bean
- @Order(Ordered.HIGHEST_PRECEDENCE)
- public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
- throws Exception {
-
- OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
- http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
- .oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0
- http
- // 未从授权终结点进行身份验证时重定向到登录页面
- .exceptionHandling((exceptions) -> exceptions
- .defaultAuthenticationEntryPointFor(
- new LoginUrlAuthenticationEntryPoint("/login"),
- new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
- )
- )
- // 接受用户信息和/或客户端注册的访问令牌
- .oauth2ResourceServer((resourceServer) -> resourceServer
- .jwt(Customizer.withDefaults()));
- return http.build();
- }
- /**
- * 配置认证相关的过滤器链
- *
- * @param http spring security核心配置类
- * @return 过滤器链
- * @throws Exception 抛出
- */
- @Bean
- @Order(2)
- SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
-
- http.authorizeHttpRequests(authorizeRequests ->
- authorizeRequests
- // 允许的请求
- .requestMatchers(HttpMethod.GET, "/test").
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |