Der*_*ble 0 spring oauth spring-security spring-security-oauth2
我有使用 spring oAuth2 的完美运行的 Spring Boot 应用程序。当我在主类上使用 @EnableResourceServer 时,它运行良好。但要为我在课下实现的服务启用 CORS
@Configuration
public class CorsConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.of("HEAD",
"GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Run Code Online (Sandbox Code Playgroud)
添加该类后,似乎请求未使用 oAuth 令牌进行验证。即使没有 oAuth 令牌的任何请求也可以访问服务。
我做错了什么?我不能两个都用吗?有什么特别的事情要做吗?有没有更好的方法来启用 CORS。(我试过@CrossOrigin 注释它没有用)
我不确定您为什么要使用WebSecurityConfigurerAdapter
我认为您的问题是您没有将您的呼叫转发给 oAuth 进行授权。试试这个对我有用
@Configuration
public class CorsConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests().anyRequest().authenticated();
}
@Bean
public CorsFilter corsFilter() {
final org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.of("HEAD",
"GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("resource");
}
}
Run Code Online (Sandbox Code Playgroud)
这里这个 resources.resourceId("resource");
应该是您在 oAuth 服务器中使用的资源
类似这样的方法
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clinet").secret("secret").accessTokenValiditySeconds(3600).scopes("read", "write")
.authorizedGrantTypes("password", "refresh_token").resourceIds("resource");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
715 次 |
最近记录: |