权限认证SpringCloud GateWay、SpringSecurity、OAuth2.0、JWT一网打尽!
在Spring Cloud Gateway中使用Spring Security和OAuth2.0进行权限认证和授权,并使用JWT作为令牌格式,可以通过以下步骤实现:
- 引入依赖:
<!-- Spring Security 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Cloud Gateway 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- OAuth2 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<!-- JWT 依赖 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
- 配置Spring Security和OAuth2.0:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 禁用CSRF保护
.authorizeRequests()
.anyRequest().authenticated() // 所有请求需要认证
.and()
.oauth2ResourceServer() // 配置资源服务器
.jwt(); // 使用JWT进行认证
}
}
- 配置Gateway路由,并添加过滤器进行权限校验:
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocator routeLocator) {
return routeLocator.routes()
.route("my_route", r -> r.path("/my/**")
.filters(f -> f.filter(new MyGatewayFilterFactory()))
.uri("http://myservice"))
.build();
}
}
public class MyGatewayFilterFactory implements GatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
// 在这里添加权限校验逻辑
// 例如,检查JWT的权限声明
ServerHttpRequest request = exchange.getRequest();
// ...
// 如果权限校验通过则调用chain.filter(exchange)继续请求
// 如果不通过则返回403 Forbidden或者重定向到登录页面
return chain.filter(exchange);
};
}
}
- 验证和授权服务器配置:
@Configuration
public class OAuth2ResourceServerConfig {
@Autowired
private AuthenticationManager authenticationMa
评论已关闭