Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 多个oauth2服务和配置_Spring_Spring Boot_Oauth 2.0 - Fatal编程技术网

Spring 多个oauth2服务和配置

Spring 多个oauth2服务和配置,spring,spring-boot,oauth-2.0,Spring,Spring Boot,Oauth 2.0,我有一个使用扩展配置的现有Spring应用程序 ResourceServerConfigureAdapter针对内部oauth服务保护API。 我正在尝试添加另一个扩展WebSecurity配置适配器的配置B,该配置针对外部oauth提供程序进行身份验证 目的是继续使用B确定/api/相关端点的身份验证,而A确定web应用程序的总体登录。 以下是使用ResourceServerConfigureAdapter的现有代码:- @Configuration @EnableResourceServer

我有一个使用扩展配置的现有Spring应用程序 ResourceServerConfigureAdapter针对内部oauth服务保护API。 我正在尝试添加另一个扩展WebSecurity配置适配器的配置B,该配置针对外部oauth提供程序进行身份验证

目的是继续使用B确定/api/相关端点的身份验证,而A确定web应用程序的总体登录。

以下是使用ResourceServerConfigureAdapter的现有代码:-

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

@Value("${oauth.clientId}")
private String clientId;

@Value("${oauth.clientSecret}")
private String clientSecret;

@Autowired
private RestTemplate restTemplate;

@Bean
public RemoteTokenServices remoteTokenServices() {
    RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
    remoteTokenServices.setRestTemplate(restTemplate);
    remoteTokenServices.setClientId(clientId);
    remoteTokenServices.setClientSecret(clientSecret);
    remoteTokenServices.setCheckTokenEndpointUrl("srvc://myservice/api/v2/oauth/check_token");
    return remoteTokenServices;
}

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources.resourceId(null);
    resources.tokenServices(remoteTokenServices());
}

@Override
public void configure(HttpSecurity http) throws Exception {
    http.anonymous()
        .and().authorizeRequests()
        .antMatchers("/api/secured/**").authenticated()
        .antMatchers("/api/**").permitAll();
}}
以下是使用WebSecurity配置适配器的代码:-

@SpringBootApplication
@EnableOAuth2Client
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class DemoService extends WebSecurityConfigurerAdapter {

    @Autowired
    OAuth2ClientContext oauth2ClientContext;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll().anyRequest()
                .authenticated().and().exceptionHandling()
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
                .logoutSuccessUrl("/").permitAll().and().csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
                .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
        // @formatter:on
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoService.class, args);
    }

    @Bean
    public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(filter);
        registration.setOrder(-100);
        return registration;
    }

    private Filter ssoFilter() {
        OAuth2ClientAuthenticationProcessingFilter googleFilter = new OAuth2ClientAuthenticationProcessingFilter(
                "/login/google");
        OAuth2RestTemplate googleTemplate = new OAuth2RestTemplate(google(), oauth2ClientContext);
        googleFilter.setRestTemplate(googleTemplate);
        UserInfoTokenServices tokenServices = new UserInfoTokenServices(googleResource().getUserInfoUri(),
                google().getClientId());
        tokenServices.setRestTemplate(googleTemplate);
        googleFilter.setTokenServices(
                new UserInfoTokenServices(googleResource().getUserInfoUri(), google().getClientId()));
        return googleFilter;
    }

    @Bean
    @ConfigurationProperties("google.client")
    public AuthorizationCodeResourceDetails google() {
        return new AuthorizationCodeResourceDetails();
    }

    @Bean
    @ConfigurationProperties("google.resource")
    public ResourceServerProperties googleResource() {
        return new ResourceServerProperties();
    }

}
它们各自运行良好,但放在同一个项目中,问题开始显现。一切编译和运行都很好,但当我点击localhost:8080/时,会发生以下情况- 页面加载正常,但当我点击localhost:8080/login/google时,它会显示一个白标签错误页面,如下所示

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Apr 06 13:22:27 IST 2017
There was an unexpected error (type=Not Found, status=404).
Not Found
我试着读了一些关于ResourceServerConfigureAdapter与WebSecurity ConfigureAdapter的比较,我只能理解有某种过滤器顺序决定了每个配置程序的优先级。但这并没有帮助我解决这个问题。有什么建议吗

更新: 还有另一个用于Swagger集成的适配器,也是项目的一部分

@EnableSwagger2
@Configuration
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/docs", "/swagger-ui.html");
        registry.addRedirectViewController("/docs/", "/swagger-ui.html");
        registry.addRedirectViewController("/docs.json", "/v2/api-docs");
    }

    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(new ApiInfoBuilder()
                .title("Spring Boot Service")
                .description("Sample project documentation")
                .contact("a@b.com")
                .version("1.0")
                .license("Apache")
                .build())
            .forCodeGeneration(true)
            .ignoredParameterTypes(Principal.class)
            .useDefaultResponseMessages(false)
            .select()
            .paths(documentedPaths())
            .build();
    }

    private Predicate<String> documentedPaths() {
        return or(
            regex("/api.*"));
    }
}
@EnableSwagger2
@配置
公共类SwaggerConfiguration扩展了WebMVCConfigureAdapter{
@凌驾
public void addViewController(ViewControllerRegistry注册表){
registry.addRedirectViewController(“/docs”,“/swagger ui.html”);
registry.addRedirectViewController(“/docs/”,“/swagger ui.html”);
registry.addRedirectViewController(“/docs.json”,“/v2/api docs”);
}
@豆子
公众卷宗招摇过市{
返回新摘要(DocumentationType.SWAGGER_2)
.apiInfo(新的ApiInfoBuilder()
.title(“Spring启动服务”)
.说明(“项目文件样本”)
.联系人(“a@b.com")
.版本(“1.0”)
.license(“Apache”)
.build())
.forCodeGeneration(真)
.ignoredParameterTypes(Principal.class)
.useDefaultResponseMessages(false)
.选择()
.paths(documentedPaths())
.build();
}
私有谓词DocumentedPath(){
返回或(
regex(“/api.”);
}
}
.addFilterBefore(ssoFilter(),BasicAuthenticationFilter.class)

OAuth2ClientAuthenticationProcessingFilter
必须在
OAuth2ClientContextFilter
之后,
OAuth2ClientAuthenticationProcessingFilter
将在请求错误(无
code
等)时引发
重定向异常

并且,
OAuth2ClientContextFilter将捕获它并重定向到
userAuthorizationUri

BasicAuthenticationFilter
位于
OAuth2ClientContextFilter
normal之前,因此您应该更改顺序:

@Autowired
private OAuth2ClientContextFilter oAuth2ClientContextFilter;

protected void configure(HttpSecurity http) throws Exception { 
    http
        .addFilterAfter(oAuth2ClientContextFilter, ExceptionTranslationFilter.class)
        .addFilterAfter(ssoFilter(), OAuth2ClientContextFilter.class);

}
更新:

还有一个地方需要更新,如果您有多个链,则应定义请求匹配,默认值为“/**”,并且
ResourceServerConfiguration
的默认顺序为3,
WebSecurityConfigureAdapter
的默认顺序为100,
ResourceServerConfiguration
具有高优先级

// only handle the request start with `/api`
http.requestMatcher(new AntPathRequestMatcher("/api/**"))
http.anonymous()
        .and().authorizeRequests()
        .antMatchers("/api/secured/**").authenticated()
        .antMatchers("/api/**").permitAll();
如果通过更改顺序将
websecurityConfigureAdapter
放在
ResourceServerConfiguration
之前,则还应将
websecurityConfigureAdapter
配置为非处理程序
/api/**

// skip the request start with '/api'
http.requestMatcher(new RegexRequestMatcher("^(?!/api).*$", null))
    .authorizeRequests().antMatchers("/", "/login/**", "/webjars/**").permitAll().anyRequest()
更新2:

.authorizeRequests().antMatchers(“/”,“/login**”)

此匹配器与
/login/google
不匹配,请更新到
/login/**
,因此应为


.authorizeRequests().antMatchers(“/”,“/login/**”).permitAll()

它没有编译,但是.addFilterAfter(ssoFilter(),SecurityContextPersistenceFilter.class)编译后仍然无法工作。你认为我需要调整configure(HttpSecurity-http)函数吗?代码可以编译,但不起作用。当我点击localhost:8080/login/google时,它仍然显示白色标签错误页面。没有例外。你的建议听起来很合理,这正是我打算做的,但我仍然会看到白色标签错误页面,这次是(401,未经授权访问)。我确信上述模式有助于克服(404,未找到)仍然获得401,身份验证失败:需要身份验证才能获得访问令牌(不允许匿名)。resourceserverconfiguration的旧代码具有“.anonymous()和()。更新后,即使将其添加回也无法使整个spring安全配置满意