要实现不使用Spring Boot的OAuth 2.0,可以使用Spring Security和OAuth 2.0的原生支持。以下是一个简单的示例:
org.springframework.security.oauth.boot
spring-security-oauth2-autoconfigure
2.3.9.RELEASE
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/api/**").authenticated()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
}
上述配置中,允许所有用户访问"/oauth/token"端点(用于获取访问令牌),但要求对"/api/**"端点进行身份验证。
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret("{noop}secret")
.authorizedGrantTypes("password", "refresh_token")
.scopes("read", "write")
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(86400);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager());
}
@Bean
public AuthenticationManager authenticationManager() {
return new AuthenticationManagerBuilder(authenticationManager());
}
}
上述配置中,定义了一个客户端(client)和它的授权类型、范围以及访问令牌和刷新令牌的有效期。
@SpringBootApplication
@EnableWebSecurity
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
以上是一个基本的不使用Spring Boot的OAuth 2.0的实现方法。请注意,此示例仅用于演示目的,并不适用于生产环境。在实际应用中,您可能需要使用数据库存储客户端和用户信息,以及配置其他安全规则和认证提供程序。