package net.wohlfart.mercury.security.oauth;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * read the code token form the servlet request and put it into the  access token request
 * so it can be detected and used by the oauth template
 */
@Slf4j
class AuthFilter extends OAuth2ClientAuthenticationProcessingFilter {

    public static final String CODE_KEY = "code";
    private final DefaultOAuth2ClientContext defaultOAuth2ClientContext;

    public AuthFilter(String defaultFilterProcessesUrl, DefaultOAuth2ClientContext defaultOAuth2ClientContext) {
        super(defaultFilterProcessesUrl);
        this.defaultOAuth2ClientContext = defaultOAuth2ClientContext;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String authCode = request.getParameter(CODE_KEY);
        if (!StringUtils.isEmpty(authCode)) {
            log.debug("<attemptAuthentication> found code: " + authCode);
            defaultOAuth2ClientContext.getAccessTokenRequest().setAuthorizationCode(authCode);
        }
        return super.attemptAuthentication(request, response);
    }

}

@@ -73,16 +73,104 @@
 .Slf4j;%0A
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;%0A
 import o
@@ -397,16 +397,90 @@
 Filter;%0A
+import org.springframework.security.oauth2.provider.OAuth2Authentication;%0A
 import o
@@ -1500,9 +1500,8 @@
 if (
-!
 Stri
@@ -1529,24 +1529,194 @@
 ode)) %7B%0A    
+        // no code yet, try and do the redirect exception and do another provider roundtrip%0A            return super.attemptAuthentication(request, response);%0A        %7D%0A%0A
         log.
@@ -1781,20 +1781,16 @@
         
-   
- 
 defaultO
@@ -1876,71 +1876,431 @@
     
-%7D%0A        return super.attemptAuthentication(request, response)
+OAuth2Authentication authentication = (OAuth2Authentication) super.attemptAuthentication(request, response);%0A        UsernamePasswordAuthenticationToken principal = (UsernamePasswordAuthenticationToken) authentication.getUserAuthentication();%0A        log.info(%22%3CattemptAuthentication%3E authentication: %7B%7D%22, authentication);%0A        log.info(%22%3CattemptAuthentication%3E principal: %7B%7D%22, principal);%0A%0A        return authentication
 ;%0A  

read details