使用Spring Security在

时间:2019-05-14 22:53:57

标签: spring spring-boot spring-security oauth-2.0 spring-security-oauth2

我正在使用Spring Boot 2.1.3和Spring Security 5.1.3实现OAuth2 Web应用程序客户端,该客户端正在通过授权代码授予类型从授权服务器获取JWT令牌,并调用受保护的资源服务器。

这是到目前为止的实现方式:

安全配置和用于调用受保护资源的restTemplate bean:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2Login()
            .and()
            .oauth2Client()
            .and().logout().logoutSuccessUrl("/");
    }

    @Bean
    public RestTemplate restTemplate(OAuth2AuthorizedClientService clientService) {
        RestTemplate restTemplate = new RestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        if (CollectionUtils.isEmpty(interceptors)) {
            interceptors = new ArrayList<>();
        }
        interceptors.add(new AuthorizationHeaderInterceptor(clientService));
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }
}

在restTemplate中添加授权标头(来自框架的InMemoryOAuth2AuthorizedClientService)的拦截器:

public class AuthorizationHeaderInterceptor implements ClientHttpRequestInterceptor {

    private OAuth2AuthorizedClientService clientService;

    public AuthorizationHeaderInterceptor(OAuth2AuthorizedClientService clientService) {
        this.clientService = clientService;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String accessToken = null;
        if (authentication != null && authentication.getClass().isAssignableFrom(OAuth2AuthenticationToken.class)) {
            OAuth2AuthenticationToken auth = (OAuth2AuthenticationToken) authentication;
            String clientRegistrationId = auth.getAuthorizedClientRegistrationId();
            OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(clientRegistrationId, auth.getName());
            accessToken = client.getAccessToken().getTokenValue();
            request.getHeaders().add("Authorization", "Bearer " + accessToken);
        }
        return execution.execute(request, bytes);
    }
}

以及调用受保护资源服务器的控制器:

@Controller
@RequestMapping("/profile")
public class ProfileController {

    @Autowired
    private RestTemplate restTemplate;

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

    @GetMapping
    public String getProfile(Model model) {
        Profile profile = restTemplate.getForEntity(resourceServerBase + "/api/profile/", Profile.class).getBody();
        model.addAttribute("profile", profile);
        return "profile";
    }
}

OAuth2客户端配置直接在application.yml中:

spring:
  security:
    oauth2:
      client:
        registration:
          auth-server:
            client-id: webClient
            client-secret: clientSecret
            scope: read,write
            authorization-grant-type: authorization_code
            redirect-uri: http://localhost:8081/client/login/oauth2/code/auth-server
        provider:
          auth-server:
            authorization-uri: http://localhost:8080/auth-server/oauth/authorize
            token-uri: http://localhost:8080/auth-server/oauth/token
            user-info-uri: http://localhost:8082/resource-server/users/info
            user-name-attribute: user_name

进行一些调试之后,我发现在通过OAuth2LoginAuthtenticationFilter成功进行身份验证流结束时,框架通过提供的InMemoryOAuth2AuthorizedClientService将OAuth2AuthorizedClient模型下获得的访问和刷新JWT令牌存储在内存中。

我正在尝试找出如何覆盖此行为,以便在服务器重新启动后令牌仍然可用。并根据此保持用户登录。

我应该只提供自定义OAuth2AuthorizedClientService实现吗?如何配置Spring Security来使用它?并且此自定义实现应将令牌存储在cookie中吗?

1 个答案:

答案 0 :(得分:0)

我应该只提供自定义的OAuth2AuthorizedClientService吗? 实施?

我认为是的,用于解决您的用例

如何配置Spring Security来使用它?

来自spring doc

  

如果您想提供以下内容的自定义实现   AuthorizationRequestRepository,用于存储以下属性   Cookie中的OAuth2AuthorizationRequest,您可以如下所示进行配置   在以下示例中:

@EnableWebSecurity
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .oauth2Client()
                .authorizationCodeGrant()
                    .authorizationRequestRepository(this.cookieAuthorizationRequestRepository())
                    ...
    }

    private AuthorizationRequestRepository<OAuth2AuthorizationRequest> cookieAuthorizationRequestRepository() {
        return new HttpCookieOAuth2AuthorizationRequestRepository();
    }
}