This commit is contained in:
孙小云 2025-07-19 14:00:11 +08:00
parent 726a29e71d
commit c198d3c6b0
7 changed files with 11 additions and 182 deletions

View File

@ -5,7 +5,12 @@
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="b713637a-3b19-4c5b-9e88-95e35dd83d2e" name="更改" comment=""> <list default="true" id="b713637a-3b19-4c5b-9e88-95e35dd83d2e" name="更改" comment="">
<change beforePath="$PROJECT_DIR$/../oidc/src/main/java/com/tuoheng/oauth/oidc/provider/CustomAuthenticationProvider.java" beforeDir="false" afterPath="$PROJECT_DIR$/../oidc/src/main/java/com/tuoheng/oauth/oidc/provider/CustomAuthenticationProvider.java" afterDir="false" /> <change beforePath="$PROJECT_DIR$/../oidc/src/main/java/com/tuoheng/oauth/oidc/config/SecurityConfig.java" beforeDir="false" afterPath="$PROJECT_DIR$/../oidc/src/main/java/com/tuoheng/oauth/oidc/config/SecurityConfig.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../oidc/src/main/java/com/tuoheng/oauth/oidc/provider/CustomAuthenticationProvider.java" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/../oidc/src/main/java/com/tuoheng/oauth/oidc/token/CustomAuthenticationToken.java" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/../oidc/src/main/resources/static/login.html" beforeDir="false" afterPath="$PROJECT_DIR$/../oidc/src/main/resources/static/login.html" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../resourceservicehtml/index.html" beforeDir="false" afterPath="$PROJECT_DIR$/../resourceservicehtml/index.html" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../resourceservicehtmlb/index.html" beforeDir="false" afterPath="$PROJECT_DIR$/../resourceservicehtmlb/index.html" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />

View File

@ -32,7 +32,6 @@ import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import com.tuoheng.oauth.oidc.provider.CustomAuthenticationProvider;
import java.security.KeyPair; import java.security.KeyPair;
import java.security.KeyPairGenerator; import java.security.KeyPairGenerator;
@ -62,18 +61,13 @@ public class SecurityConfig {
exceptions.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")) exceptions.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
); );
// // 允许OIDC发现端点公开访问
// http.authorizeHttpRequests(authorize ->
// authorize.requestMatchers("/.well-known/openid_configuration").permitAll()
// );
return http.build(); return http.build();
} }
// 配置应用安全过滤器链 // 配置应用安全过滤器链
@Bean @Bean
@Order(2) @Order(2)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, CustomAuthenticationProvider customAuthenticationProvider) throws Exception { public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http http
.authorizeHttpRequests(authorize -> .authorizeHttpRequests(authorize ->
authorize authorize
@ -85,7 +79,6 @@ public class SecurityConfig {
.anyRequest().authenticated() .anyRequest().authenticated()
) )
.oauth2ResourceServer(oauth2 -> oauth2.jwt()) // 新增支持JWT .oauth2ResourceServer(oauth2 -> oauth2.jwt()) // 新增支持JWT
.authenticationProvider(customAuthenticationProvider) // 添加自定义认证提供者
.formLogin(form -> form .formLogin(form -> form
.loginPage("/login") .loginPage("/login")
.loginProcessingUrl("/login") .loginProcessingUrl("/login")
@ -206,6 +199,4 @@ public class SecurityConfig {
public PasswordEncoder passwordEncoder() { public PasswordEncoder passwordEncoder() {
return new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder(); return new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder();
} }
} }

View File

@ -1,88 +0,0 @@
package com.tuoheng.oauth.oidc.provider;
import com.tuoheng.oauth.oidc.token.CustomAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;
/**
* 自定义认证提供者处理包含租户代码和客户端ID的认证
*/
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (authentication instanceof UsernamePasswordAuthenticationToken) {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
// 获取HttpServletRequest来读取表单参数
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String tenantCode = null;
String clientId = null;
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
tenantCode = request.getParameter("tenant_code");
clientId = request.getParameter("client_id");
}
// 打印接收到的参数用于验证
System.out.println("=== 认证参数验证 ===");
System.out.println("用户名: " + username);
System.out.println("密码: " + password);
System.out.println("租户代码: " + tenantCode);
System.out.println("客户端ID: " + clientId);
//这边需要从数据库获取数据做校验
// 6. 创建认证成功的自定义Token
System.out.println("认证成功 - 用户: " + username + ", 租户: " + tenantCode + ", 客户端: " + clientId);
// 创建用户详情和权限
UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
.username(username)
.password(passwordEncoder.encode(password))
.roles("USER")
.build();
// 创建已认证的Token包含权限信息
return new CustomAuthenticationToken(userDetails, password, userDetails.getAuthorities(), tenantCode, clientId);
}
return null;
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
/**
* 验证用户名和密码
* 这里可以自定义验证逻辑比如查询数据库
*/
private boolean isValidUser(String username, String password) {
// 这里使用简单的硬编码验证实际应用中应该查询数据库
return ("user".equals(username) && "password".equals(password)) ||
("admin".equals(username) && "admin123".equals(password)) ||
("user2".equals(username) && "password2".equals(password));
}
}

View File

@ -1,61 +0,0 @@
package com.tuoheng.oauth.oidc.token;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
/**
* 自定义认证Token包含租户代码和客户端ID
*/
public class CustomAuthenticationToken extends UsernamePasswordAuthenticationToken {
private final String tenantCode;
private final String clientId;
/**
* 构造函数 - 用于认证请求
*/
public CustomAuthenticationToken(Object principal, Object credentials, String tenantCode, String clientId) {
super(principal, credentials);
this.tenantCode = tenantCode;
this.clientId = clientId;
}
/**
* 构造函数 - 用于已认证的token
*/
public CustomAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities, String tenantCode, String clientId) {
super(principal, credentials, authorities);
this.tenantCode = tenantCode;
this.clientId = clientId;
}
/**
* 获取租户代码
*/
public String getTenantCode() {
return tenantCode;
}
/**
* 获取客户端ID
*/
public String getClientId() {
return clientId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
if (tenantCode != null) {
sb.append("; TenantCode: ").append(tenantCode);
}
if (clientId != null) {
sb.append("; ClientId: ").append(clientId);
}
return sb.toString();
}
}

View File

@ -150,7 +150,6 @@
<form id="login-form" method="post" action="/login"> <form id="login-form" method="post" action="/login">
<input type="hidden" id="csrf-parameter" name="" value="" /> <input type="hidden" id="csrf-parameter" name="" value="" />
<input type="hidden" id="client-id" name="client_id" value="" />
<div class="form-group"> <div class="form-group">
<label for="username">用户名</label> <label for="username">用户名</label>
@ -164,7 +163,7 @@
<div class="form-group"> <div class="form-group">
<label for="tenant-code">租户代码</label> <label for="tenant-code">租户代码</label>
<input type="text" id="tenant-code" name="tenant_code" placeholder="请输入租户代码" autocomplete="off"> <input type="text" id="tenant-code" name="tenant-code" placeholder="请输入租户代码" autocomplete="off">
</div> </div>
<div class="checkbox-group"> <div class="checkbox-group">
@ -181,17 +180,11 @@
</div> </div>
<script> <script>
// 页面加载时检查错误参数和设置client_id // 页面加载时检查错误参数
window.addEventListener('DOMContentLoaded', function() { window.addEventListener('DOMContentLoaded', function() {
// 检查是否有错误参数 // 检查是否有错误参数
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const error = urlParams.get('error'); const error = urlParams.get('error');
const clientId = urlParams.get('client_id');
// 设置client_id到隐藏字段
if (clientId) {
document.getElementById('client-id').value = clientId;
}
if (error) { if (error) {
const errorMessage = document.getElementById('error-message'); const errorMessage = document.getElementById('error-message');

View File

@ -168,11 +168,7 @@
authUrl.searchParams.set('scope', oidcConfig.scope); authUrl.searchParams.set('scope', oidcConfig.scope);
authUrl.searchParams.set('state', state); authUrl.searchParams.set('state', state);
// 将client_id作为参数传递到登录页面 window.location.href = authUrl.toString();
const loginUrl = new URL('https://oidc.local.com/login');
loginUrl.searchParams.set('client_id', oidcConfig.clientId);
window.location.href = loginUrl.toString();
} }
// 处理回调 // 处理回调

View File

@ -88,7 +88,6 @@
// 页面加载时执行 // 页面加载时执行
window.onload = function() { window.onload = function() {
console.log("页面加载完成");
if (code) { if (code) {
// 有授权码,处理回调 // 有授权码,处理回调
handleCallback(code, state); handleCallback(code, state);
@ -150,7 +149,6 @@
// 显示登录部分 // 显示登录部分
function showLoginSection() { function showLoginSection() {
console.log("显示登录部分");
document.getElementById('status').className = 'status info'; document.getElementById('status').className = 'status info';
document.getElementById('status').textContent = '请登录以继续'; document.getElementById('status').textContent = '请登录以继续';
@ -170,12 +168,7 @@
authUrl.searchParams.set('scope', oidcConfig.scope); authUrl.searchParams.set('scope', oidcConfig.scope);
authUrl.searchParams.set('state', state); authUrl.searchParams.set('state', state);
// 将client_id作为参数传递到登录页面 window.location.href = authUrl.toString();
const loginUrl = new URL('https://oidc.local.com/login');
console.log("--------loginUrl--------", loginUrl);
loginUrl.searchParams.set('client_id', oidcConfig.clientId);
window.location.href = loginUrl.toString();
} }
// 处理回调 // 处理回调