SarangRN
SarangRN

Reputation: 140

Unable to logout using spring security OidcClientInitiatedLogoutSuccessHandler from ADFS server

When I do log out, It should redirect to end_session_endpoint of ADFS which is "https://fed04.xxxxxxx.com/adfs/oauth2/logout" however it's redirecting back to the home page without prompting for login.

spring security OAuth client configuration for the web app Updates: I have also added issuer-URI as follows.

spring:
  security:
    oauth2:
      client:
        registration:
          adfs: 
            client-id: XXXXX-XXXX-XXXX-XXXXX
            scope: openid,email
            redirect-uri: https://<app_domain>.azurewebsites.net/home
            client-authentication-method: basic
            authorization-grant-type: authorization_code
        provider:
          adfs:
            authorization-uri: https://<domain>/adfs/oauth2/authorize?resource=<web-api-identifier>
            token-uri: https://<domain>/adfs/oauth2/token
            user-info-authentication-method: query
            jwk-set-uri: https://<domain>/adfs/discovery/keys
            user-name-attribute: upn
            user-info-uri: https://<domain>/adfs/userinfo
            issuer-uri: https://<domain>/adfs

SecurityConfig.java


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    

    
    @Autowired
    ClientRegistrationRepository clientRegistrationRepository; 
    
    private OidcClientInitiatedLogoutSuccessHandler oidcLogoutSuccessHandler() { 
        OidcClientInitiatedLogoutSuccessHandler successHandler = new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
        successHandler.setPostLogoutRedirectUri("https://<app_domain>.azurewebsites.net");
        return successHandler;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
          .antMatchers("/home", "/login**","/callback/", "/webjars/**", "/error**", "/oauth2/authorization/**")
          .permitAll()
          .anyRequest()
          .authenticated()
          .and()
          .logout()
//          .logoutSuccessHandler(myLogoutHandler)
          .logoutSuccessHandler(oidcLogoutSuccessHandler())
          .invalidateHttpSession(true)
          .clearAuthentication(true)
          //.permitAll()
          .and() 
          .oauth2Login();
    
}

Upvotes: 2

Views: 1014

Answers (1)

SarangRN
SarangRN

Reputation: 140

If you are using azure web app, please add AFDS domain URL in CORS setting or use custom logout handler.

enter image description here

// Also you can use custom logout handler. Changes in the configuration as follows 
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
          .antMatchers("/home", "/login**","/callback/", "/webjars/**", "/error**", "/oauth2/authorization/**")
          .permitAll()
          .anyRequest()
          .authenticated()
          .and()
          .logout()
          .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
          .addLogoutHandler(logoutHandler) // for custom logout
          .and() 
          .oauth2Login();

    http.csrf().disable();

// Added new custom logout as follows 

@Component
public class CustomLogoutHandler implements LogoutHandler {

    @Autowired
    ResourceConfig resourceConfig;

    private static Logger logger = LogManager.getLogger(CustomLogoutHandler.class);

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        try {

            logger.info("custom logout executed");

            String idToken = "";
            if (request.getSession() != null) {
                logger.info("invalidate session details");
                AuthResults results = (AuthResults) request.getSession()
                        .getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
                if (results != null) {
                    idToken = results.getIdToken();
                }
                request.getSession().invalidate();
            }
            // Clearing all cookies
            if (request.getCookies() != null) {
                logger.info("Clearing all cookies");
                for (Cookie cookie : request.getCookies()) {
                    cookie.setMaxAge(0);
                }
            }
            if (!"".equals(idToken)) {
                logger.info("redirecting with post logout redirect url");
                response.sendRedirect(Constants.LOGOUT_TOKEN_URL+ idToken);
            } else {
                logger.info("redirecting without post logout redirect url");
                response.sendRedirect(Constants.LOGOUT_URL);
            }
        } catch (IOException e) {
            logger.error("Error occured in logout Method ",e);
        }
    }

    ```

Upvotes: 0

Related Questions