Spring Security+OAuth2.0+OIDC1.0
文章目录
前言
之前学习springboot集成spring security的OAauth2.1和OIDC1.0遇到的问题及成功情况,这里做个笔记下次好查看。
一、准备工作
1.Spring Security相关依赖包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
...
<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.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
</dependency>
2.先看下Authorization Code Grant经典图
2.还是画个结构草图
二、创建对应微服务
1.创建springboot-oauth2-server服务
结构如下所示:
核心类MyAuthorizationServerConfig如下:
package com.example.demo.config;
...
@EnableWebSecurity
public class MyAuthorizationServerConfig {
@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
// // Redirect to the login page when not authenticated from the
// // authorization endpoint
// http.exceptionHandling((exceptions) -> exceptions
// .authenticationEntryPoint(
// new LoginUrlAuthenticationEntryPoint("/login"))
// );
http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
//customized authorizationEndpoint,redirectionEndpoint,tokenEndpoint,userInfoEndpoint
// http.oauth2Login(oauth2 -> oauth2.userInfoEndpoint(userinfo ->
// userinfo.oidcUserService(oauth2UserService())
// )
// .oauth2.tokenEndpoint(...)
// );
//if defined http.exceptionHandling then no need to define http.formLogin(Customizer.withDefaults())
return http.formLogin(Customizer.withDefaults()).build();
}
//for authorization_code purpose
@Bean
@Order(2)
public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests