以下是一个简化的示例,展示了如何在Spring Boot应用中使用Spring Security和OAuth2.0结合JWT实现统一认证和授权。
// 引入相关依赖的配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 禁用CSRF保护
.authorizeRequests()
.antMatchers("/login/**").permitAll() // 允许登录路径无授权访问
.anyRequest().authenticated() // 其他所有请求需要认证
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager())); // 添加JWT认证过滤器
}
// 其他配置...
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client") // 客户端ID
.secret("secret") // 客户端秘钥
.authorizedGrantTypes("password", "refresh_token") // 授权类型
.scopes("read", "write") // 权限范围
.accessTokenValiditySeconds(1800) // 访问令牌有效期(秒)
.refreshTokenValiditySeconds(3600); // 刷新令牌有效期(秒)
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
}
// JWT认证过滤器
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManage