Spring Security统一认证接入方案(仅供参考)
背景
将老ASP系统升级为Java系统,并接入大平台统一认证体系,实现通过大平台登录后跳转到原有系统免登录功能。
技术实现方案
1. Spring Security配置
在Security配置中添加统一登录的链接访问许可:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/unified-login").permitAll() // 统一登录入口
// 其他配置...
// 其他安全配置...
}
}
2. 实现UserDetailsService
自定义UserService实现UserDetailsService接口:
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.selectOne(new QueryWrapper<User>().eq("UserName", username));
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
String roles = String.valueOf(user.getUserType());
return User.builder()
.username(user.getUserName())
.password(user.getPass())
.roles(roles)
.build();
}
}
3. 控制器处理统一认证
@Controller
public class AuthController {
@Autowired
private UserService userService;
@Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
@GetMapping("/unified-login")
public void unifiedLogin(UserInfo userinfo, HttpServletRequest request,
HttpServletResponse response, HttpSession session) {
// 加载用户信息
UserDetails userDetails = userService.loadUserByUsername(userinfo.getUserName());
// 创建认证对象
Authentication auth = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
// 设置认证上下文
SecurityContextHolder.getContext().setAuthentication(auth);
// 保存到session中
session.setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext());
// 跳转到登录成功处理
customAuthenticationSuccessHandler.onAuthenticationSuccess(
request, response, auth);
}
}
4. 自定义认证成功处理器
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
// 自定义成功处理逻辑
response.sendRedirect("/home"); // 示例:跳转到首页
}
}
关键点说明
- 统一认证入口:通过
/unified-login端点接收大平台跳转请求 - 用户信息加载:通过实现
UserDetailsService接口加载本地用户信息 - 认证流程:
- 创建
UsernamePasswordAuthenticationToken - 设置
SecurityContext - 保存到Session
- 调用成功处理器
- 创建
- 会话保持:通过
HttpSessionSecurityContextRepository保持登录状态
注意事项
- 确保统一认证入口的安全性,防止未经验证的请求
- 用户角色转换需要根据业务需求调整
- 密码处理应根据实际情况考虑加密方式
- 成功跳转逻辑可根据业务需求定制
此方案实现了从大平台统一认证到本地系统的无缝衔接,保持了Spring Security的安全机制,同时兼容原有系统的用户体系。