|
| 1 | +/* |
| 2 | + * This file is part of the Tansen project. |
| 3 | + * |
| 4 | + * For the full copyright and license information, please view the LICENSE |
| 5 | + * file that was distributed with this source code. |
| 6 | + */ |
| 7 | +package com.ideasbucket.tansen.configuration.auth; |
| 8 | + |
| 9 | +import static com.ideasbucket.tansen.util.JsonConverter.createObjectNode; |
| 10 | +import static com.ideasbucket.tansen.util.RequestResponseUtil.*; |
| 11 | + |
| 12 | +import java.net.URI; |
| 13 | +import java.util.Map; |
| 14 | +import org.springframework.beans.factory.annotation.Autowired; |
| 15 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; |
| 16 | +import org.springframework.context.annotation.Bean; |
| 17 | +import org.springframework.context.annotation.Configuration; |
| 18 | +import org.springframework.http.HttpMethod; |
| 19 | +import org.springframework.http.HttpStatus; |
| 20 | +import org.springframework.http.server.reactive.ServerHttpResponse; |
| 21 | +import org.springframework.security.config.Customizer; |
| 22 | +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; |
| 23 | +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; |
| 24 | +import org.springframework.security.config.oauth2.client.CommonOAuth2Provider; |
| 25 | +import org.springframework.security.config.web.server.ServerHttpSecurity; |
| 26 | +import org.springframework.security.oauth2.client.oidc.web.server.logout.OidcClientInitiatedServerLogoutSuccessHandler; |
| 27 | +import org.springframework.security.oauth2.client.registration.ClientRegistration; |
| 28 | +import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository; |
| 29 | +import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; |
| 30 | +import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; |
| 31 | +import org.springframework.security.web.server.SecurityWebFilterChain; |
| 32 | +import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler; |
| 33 | +import org.springframework.security.web.server.csrf.CookieServerCsrfTokenRepository; |
| 34 | +import org.springframework.security.web.server.csrf.CsrfToken; |
| 35 | +import org.springframework.security.web.server.csrf.ServerCsrfTokenRequestHandler; |
| 36 | +import org.springframework.security.web.server.csrf.XorServerCsrfTokenRequestAttributeHandler; |
| 37 | +import org.springframework.web.server.WebFilter; |
| 38 | +import reactor.core.publisher.Mono; |
| 39 | + |
| 40 | +@Configuration |
| 41 | +@EnableWebFluxSecurity |
| 42 | +@EnableReactiveMethodSecurity |
| 43 | +@ConditionalOnProperty(value = "auth.type", havingValue = "oauth2") |
| 44 | +public class OAuth2SecurityConfiguration { |
| 45 | + |
| 46 | + private final AuthenticationProperties authenticationProperties; |
| 47 | + private final ReactiveClientRegistrationRepository clientRegistrationRepository; |
| 48 | + |
| 49 | + @Autowired |
| 50 | + public OAuth2SecurityConfiguration(AuthenticationProperties authenticationProperties) { |
| 51 | + this.authenticationProperties = authenticationProperties; |
| 52 | + this.clientRegistrationRepository = new InMemoryReactiveClientRegistrationRepository(oktaClientRegistration()); |
| 53 | + } |
| 54 | + |
| 55 | + @Bean |
| 56 | + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { |
| 57 | + CookieServerCsrfTokenRepository csrfTokenRepository = CookieServerCsrfTokenRepository.withHttpOnlyFalse(); |
| 58 | + XorServerCsrfTokenRequestAttributeHandler delegate = new XorServerCsrfTokenRequestAttributeHandler(); |
| 59 | + // Use only the handle() method of XorServerCsrfTokenRequestAttributeHandler and the |
| 60 | + // default implementation of resolveCsrfTokenValue() from ServerCsrfTokenRequestHandler |
| 61 | + ServerCsrfTokenRequestHandler csrfTokenRequestHandler = delegate::handle; |
| 62 | + |
| 63 | + return http |
| 64 | + .authorizeExchange(authorizeExchangeSpec -> { |
| 65 | + authorizeExchangeSpec.pathMatchers(HttpMethod.OPTIONS).permitAll(); |
| 66 | + authorizeExchangeSpec.pathMatchers(HttpMethod.GET, "/insight/health/readiness").permitAll(); |
| 67 | + authorizeExchangeSpec.pathMatchers(HttpMethod.GET, "/insight/health/liveness").permitAll(); |
| 68 | + authorizeExchangeSpec.pathMatchers(HttpMethod.GET, "/authentication").permitAll(); |
| 69 | + authorizeExchangeSpec.pathMatchers(HttpMethod.GET, "/login**").permitAll(); |
| 70 | + authorizeExchangeSpec.pathMatchers(HttpMethod.GET, "/oauth2/**").permitAll(); |
| 71 | + authorizeExchangeSpec.pathMatchers(HttpMethod.GET, "/favicon.ico").permitAll(); |
| 72 | + authorizeExchangeSpec.pathMatchers(HttpMethod.GET, "/assets/**").permitAll(); |
| 73 | + authorizeExchangeSpec.anyExchange().authenticated(); |
| 74 | + }) |
| 75 | + .formLogin(formLoginSpec -> formLoginSpec.loginPage("/login")) |
| 76 | + .csrf(csrfSpec -> { |
| 77 | + csrfSpec.csrfTokenRepository(csrfTokenRepository); |
| 78 | + csrfSpec.csrfTokenRequestHandler(csrfTokenRequestHandler); |
| 79 | + }) |
| 80 | + .logout(logoutSpec -> { |
| 81 | + logoutSpec.logoutUrl("/logout"); |
| 82 | + logoutSpec.logoutSuccessHandler(oidcLogoutSuccessHandler(this.clientRegistrationRepository)); |
| 83 | + }) |
| 84 | + .oauth2Login(Customizer.withDefaults()) |
| 85 | + .exceptionHandling(exceptionHandlingSpec -> { |
| 86 | + exceptionHandlingSpec.authenticationEntryPoint((serverWebExchange, ex) -> { |
| 87 | + if (isAjaxRequest(serverWebExchange.getRequest().getHeaders())) { |
| 88 | + var rootNode = createObjectNode(); |
| 89 | + rootNode.put("success", false); |
| 90 | + var errorsNode = createObjectNode(); |
| 91 | + errorsNode.put("loginUrl", getLoginPath(authenticationProperties)); |
| 92 | + errorsNode.put("message", "Login required."); |
| 93 | + rootNode.replace("errors", errorsNode); |
| 94 | + |
| 95 | + return setJsonResponse(rootNode, serverWebExchange, HttpStatus.UNAUTHORIZED); |
| 96 | + } |
| 97 | + |
| 98 | + return Mono.fromRunnable(() -> { |
| 99 | + ServerHttpResponse response = serverWebExchange.getResponse(); |
| 100 | + response.setStatusCode(HttpStatus.TEMPORARY_REDIRECT); |
| 101 | + response.getHeaders().set("Referer", serverWebExchange.getRequest().getPath().value()); |
| 102 | + response.getHeaders().setLocation(URI.create(getLoginPath(authenticationProperties))); |
| 103 | + }); |
| 104 | + }); |
| 105 | + |
| 106 | + exceptionHandlingSpec.accessDeniedHandler((serverWebExchange, ex) -> { |
| 107 | + var rootNode = createObjectNode(); |
| 108 | + rootNode.put("success", false); |
| 109 | + var errorsNode = createObjectNode(); |
| 110 | + errorsNode.put("access", "You do not have access to this action."); |
| 111 | + rootNode.replace("errors", errorsNode); |
| 112 | + |
| 113 | + return setJsonResponse(rootNode, serverWebExchange, HttpStatus.FORBIDDEN); |
| 114 | + }); |
| 115 | + }) |
| 116 | + .build(); |
| 117 | + } |
| 118 | + |
| 119 | + @Bean |
| 120 | + public ReactiveClientRegistrationRepository clientRegistrationRepository() { |
| 121 | + return this.clientRegistrationRepository; |
| 122 | + } |
| 123 | + |
| 124 | + @Bean |
| 125 | + WebFilter csrfCookieWebFilter() { |
| 126 | + return (exchange, chain) -> { |
| 127 | + Mono<CsrfToken> csrfToken = exchange.getAttributeOrDefault(CsrfToken.class.getName(), Mono.empty()); |
| 128 | + return csrfToken |
| 129 | + .doOnSuccess(token -> { |
| 130 | + /* Ensures the token is subscribed to. */ |
| 131 | + }) |
| 132 | + .then(chain.filter(exchange)); |
| 133 | + }; |
| 134 | + } |
| 135 | + |
| 136 | + private ServerLogoutSuccessHandler oidcLogoutSuccessHandler(final ReactiveClientRegistrationRepository repository) { |
| 137 | + var successHandler = new OidcClientInitiatedServerLogoutSuccessHandler(repository); |
| 138 | + successHandler.setPostLogoutRedirectUri("{baseUrl}"); |
| 139 | + |
| 140 | + return successHandler; |
| 141 | + } |
| 142 | + |
| 143 | + private ClientRegistration oktaClientRegistration() { |
| 144 | + return CommonOAuth2Provider.OKTA |
| 145 | + .getBuilder("okta") |
| 146 | + .clientId(authenticationProperties.getOauth2().getClient("okta").getClientId()) |
| 147 | + .clientSecret(authenticationProperties.getOauth2().getClient("okta").getClientSecret()) |
| 148 | + .authorizationUri(authenticationProperties.getOauth2().getClient("okta").getAuthorizationUri()) |
| 149 | + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") |
| 150 | + .scope(authenticationProperties.getOauth2().getClient("okta").getScope()) |
| 151 | + .tokenUri(authenticationProperties.getOauth2().getClient("okta").getTokenUri()) |
| 152 | + .userInfoUri(authenticationProperties.getOauth2().getClient("okta").getUserInfoUri()) |
| 153 | + .jwkSetUri(authenticationProperties.getOauth2().getClient("okta").getJwkSetUri()) |
| 154 | + .userNameAttributeName(IdTokenClaimNames.SUB) |
| 155 | + .clientName("Okta") |
| 156 | + .providerConfigurationMetadata( |
| 157 | + Map.of( |
| 158 | + "end_session_endpoint", |
| 159 | + authenticationProperties.getOauth2().getClient("okta").getSessionEndPointUri() |
| 160 | + ) |
| 161 | + ) |
| 162 | + .build(); |
| 163 | + } |
| 164 | +} |
0 commit comments