Design and Implementation of a Unified Authentication Center Using Spring Security OAuth2
This article provides a step‑by‑step tutorial on building a unified authentication center with Spring Security OAuth2, covering project module planning, authorization and resource server configuration, client module setup, gateway integration, and custom security components, complete with Maven dependencies and Java code examples.
The guide starts with a clear module layout for the authentication system, defining common, auth, system, gateway, and business modules such as qriver-common, qriver-auth (including qriver-auth-server, qriver-res-auth, qriver-auth-client), qriver-sys, qriver-gateway, and business modules moduleA and moduleB.
1. Authorization Server
The authorization server is built on Spring Security OAuth2. Required Maven dependencies include Spring Boot starters, Spring Cloud OAuth2, Nacos discovery, FastJSON, Druid, and MySQL connector. The AuthorizationServerConfig class extends AuthorizationServerConfigurerAdapter and configures token security, client details, token services, and authorization code storage.
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Resource
public DruidDataSource dataSource;
@Autowired
private PasswordEncoder passwordEncoder;
// ... configure methods omitted for brevity ...
}2. Spring Security Configuration
A custom QriverSecurityConfig extends WebSecurityConfigurerAdapter, defines a NoOpPasswordEncoder, and sets up HTTP security to permit OAuth endpoints and a custom login page.
@Configuration
public class QriverSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth/**").permitAll()
.and().formLogin().loginPage("/login")
.and().csrf().disable();
}
}3. Custom UserDetailsService
The QriverUserDetailsService loads user information via a Feign client UpmsFeignApiClient and builds a Spring Security UserDetails object.
@Component("userDetailsService")
public class QriverUserDetailsService implements UserDetailsService {
@Autowired
private UpmsFeignApiClient upmsFeignApiClient;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
String userInfo = upmsFeignApiClient.loadUserByUsername(username);
JSONObject userJson = JSON.parseObject(userInfo);
return new User(userJson.getString("username"), userJson.getString("password"), new ArrayList<>());
}
}4. Client Module (qriver-auth-client)
The client module provides common OAuth2 client configuration, using opaque token introspection. Its application.yml defines client ID, secret, and introspection URI, while AuthClientConfig sets up a RestTemplate and configures HTTP security.
@Configuration
public class AuthClientConfig extends WebSecurityConfigurerAdapter {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable();
http.oauth2ResourceServer().opaqueToken();
}
}5. Unified Gateway
The gateway aggregates services via Nacos discovery and Spring Cloud Gateway, adding OAuth2 client support and a global filter that propagates and refreshes tokens. Dependencies include spring-cloud-starter-alibaba-nacos-discovery, spring-cloud-starter-gateway, and OAuth2 client libraries.
@Component
public class SecurityGlobalFilter implements GlobalFilter, Ordered {
@Autowired
private ServerOAuth2AuthorizedClientRepository serverOAuth2AuthorizedClientRepository;
@Autowired
private ReactiveOAuth2AuthorizedClientManager reactiveOAuth2AuthorizedClientManager;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// Retrieve token from session, refresh if expired, add Authorization header
// ... implementation omitted for brevity ...
return chain.filter(exchange);
}
@Override
public int getOrder() { return 0; }
}6. Conclusion
The article demonstrates a complete, production‑ready authentication center based on Spring Security OAuth2 with opaque tokens, covering backend service design, security configuration, client integration, and gateway token relay, and hints at future migration to JWT‑based tokens.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
