Spring Security (httpsecurity)和keydrope设置

iibxawm4  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(185)

我有以下设置:
以Angular 为基础的前端,与
基于java的后端,它反过来进行通信
与组织中的第三方服务。
前端/后端访问由oauth2保护,oauth2查询KeyClope服务器。这个key斗篷服务器对我的应用程序和我的后端正在访问的第三方服务的用户进行身份验证。获取第三方服务的访问令牌的代码如下(事实上,这是出现问题的代码:调用 template.getAccessToken() ,另见下文):

private void setAccessToken(HttpRequest request) {
    HttpHeaders headers = new HttpHeaders();
    OAuth2RestTemplate template = new OAuth2RestTemplate(resourceOwnerDetails());
    OAuth2AccessToken accessToken = template.getAccessToken();
    headers.setAuthorization("Bearer " + accessToken);
    request.setHeaders(headers);
  }

安全配置如下:

@Override
  protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
      http.requiresChannel()
          .anyRequest()
          .requiresSecure()
          .and()
          .cors()
          .and()
          .csrf()
          .disable()
          .sessionManagement()
          .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
          .sessionAuthenticationStrategy(sessionAuthenticationStrategy())
          .and()
          .authorizeRequests()
          .antMatchers("/accessdenied", "/accessdenied/**", "/style/*")
          .permitAll()
          .antMatchers("/")
          .hasAnyRole(allowedRoles)
          .anyRequest()
          .hasAnyRole(allowedRoles)
          .and()
          .exceptionHandling()
          .accessDeniedPage("/accessdenied");

当需要对前端/gui访问和后端查询的第三方服务进行身份验证时,这可以正常工作。
我的问题如下:在某些条件下(tester),我希望用户不必为frontend/gui访问进行身份验证。但是,为了访问第三方服务,总是需要身份验证。
要在没有身份验证的情况下访问前端,我可以执行以下简单配置:

http.authorizeRequests().antMatchers("/**").permitAll().and().csrf().disable();

这样,我就可以访问gui而无需进行身份验证(这正是我想要的),但是当涉及到通过获取oauth2访问令牌时 template.getAccessToken() (见上图)抛出异常

org.springframework.security.authentication.InsufficientAuthenticationException: Authentication is required to obtain an access token (anonymous not allowed)

所以,我想我要找的是正确的安全配置。如何配置spring security,使其不验证gui/前端访问,但仍然获得第三方服务的访问令牌?任何指向正确方向的指针都是非常感谢的。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题