资源服务器配置完全指南前言OAuth2资源服务器用于保护API资源验证访问令牌的有效性。一、资源服务器配置1.1 基础配置spring: security: oauth2: resourceserver: jwt: issuer-uri: http://auth-server:80801.2 自定义验证Configuration EnableWebSecurity public class ResourceServerConfig { Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf - csrf.disable()) .authorizeHttpRequests(auth - auth .requestMatchers(/api/public/**).permitAll() .requestMatchers(/api/admin/**).hasAuthority(SCOPE_admin) .requestMatchers(/api/user/**).hasAuthority(SCOPE_user) .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 - oauth2 .jwt(jwt - jwt .jwtAuthenticationConverter(jwtAuthenticationConverter()) ) ); return http.build(); } Bean public JwtAuthenticationConverter jwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter new JwtGrantedAuthoritiesConverter(); grantedAuthoritiesConverter.setAuthoritiesClaimName(roles); grantedAuthoritiesConverter.setAuthorityPrefix(ROLE_); JwtAuthenticationConverter jwtAuthenticationConverter new JwtAuthenticationConverter(); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter( grantedAuthoritiesConverter); return jwtAuthenticationConverter; } }二、总结资源服务器配置是保护API安全的关键通过JWT验证可以实现无状态的认证授权。
资源服务器配置完全指南
资源服务器配置完全指南前言OAuth2资源服务器用于保护API资源验证访问令牌的有效性。一、资源服务器配置1.1 基础配置spring: security: oauth2: resourceserver: jwt: issuer-uri: http://auth-server:80801.2 自定义验证Configuration EnableWebSecurity public class ResourceServerConfig { Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf - csrf.disable()) .authorizeHttpRequests(auth - auth .requestMatchers(/api/public/**).permitAll() .requestMatchers(/api/admin/**).hasAuthority(SCOPE_admin) .requestMatchers(/api/user/**).hasAuthority(SCOPE_user) .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 - oauth2 .jwt(jwt - jwt .jwtAuthenticationConverter(jwtAuthenticationConverter()) ) ); return http.build(); } Bean public JwtAuthenticationConverter jwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter new JwtGrantedAuthoritiesConverter(); grantedAuthoritiesConverter.setAuthoritiesClaimName(roles); grantedAuthoritiesConverter.setAuthorityPrefix(ROLE_); JwtAuthenticationConverter jwtAuthenticationConverter new JwtAuthenticationConverter(); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter( grantedAuthoritiesConverter); return jwtAuthenticationConverter; } }二、总结资源服务器配置是保护API安全的关键通过JWT验证可以实现无状态的认证授权。