How Can I Customize Login Page for Oauth2 in Spring Webflux? - spring

I just want to override default oauth2 login url (/login). How can I do that? The config I have tried without success:
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange().pathMatchers(permittedUrls).permitAll()
.anyExchange().authenticated()
.and()
.oauth2Login(Customizer.withDefaults()).formLogin().loginPage("/oauth2_login")
.authenticationSuccessHandler(this::onAuthenticationSuccess)
.and()
.csrf().disable();
return http.build();
I was hoping it will redirect to /oauth2_login url but it didn't work. It still redirect to /login. But this time it returns 404 instead of showing default login page.

The code above is customizing the login page for formLogin which is typically username/password based log in from a form. It's much easier to see what configuration you are impacting using the new lambda style approach, so I have updated the entire configuration to use it. If you want to customize the login page for oauth2Login, then you should change the login page on it. For example:
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.pathMatchers(permittedUrls).permitAll()
.anyExchange().authenticated()
)
.oauth2Login(oauth2 -> oauth2
// you now must render a log in page for the URL /login
.loginPage("/login")
);
// remove formLogin that was for a username/password based log in
// if you are doing oauth2 login I'm guessing you allow users to work within a browser, so you should not disable csrf
return http.build();
}

Related

Setup custom 403 error page with Spring Boot 3 and Thymeleaf

I recently upgraded to spring boot 3 in an application with Thymeleaf, and my custom 403 pages are no longer working.
Prior to the upgrade, I believe this line was key:
http.exceptionHandling().defaultAuthenticationEntryPointFor(new Http403ForbiddenEntryPoint(), new AntPathRequestMatcher("/**"));
Since the upgrade, when I'm not authenticated and try to access a restricted page, I just get this default error screen. This my security filter chain.
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeHttpRequests(requests -> requests
.requestMatchers("/",
"/login",
"/css/**",
"/js/**",
"/images/**",
"/static/favicon.ico",
"/favicon.ico",
"/fullscreen").permitAll()
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.permitAll()
)
.logout(logout -> logout
.logoutSuccessUrl("/logout-success")
.permitAll())
.exceptionHandling()
.defaultAuthenticationEntryPointFor(new Http403ForbiddenEntryPoint(), new AntPathRequestMatcher("/**"));
return http.build();
When logged in, my 404 and 500 error pages work as expected. I think there is something missing in the way I setup the security filter chain that is preventing this custom 403 error page from working. I couldn't find any resources on how to achieve this with spring boot 3. Any suggestions?
Thanks to the comments from #dur, the solution was to add spring.security.filter.dispatcher-types=request to my application.properties file.

Spring PKCE flow with custom login page

Hi I have a spring application using PKCE flow, I want to use custom login page in angular application (actually I use defaul login page spring app), follow my configuration in spring:
#Bean
public SecurityFilterChain resourcedefaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/categorias").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthenticationConverter());
http.logout(logoutConfig -> logoutConfig.logoutSuccessHandler((request, response, auth) -> {
var returnTo = request.getParameter("returnTo");
if (StringUtils.isBlank(returnTo)){
returnTo = algamoneyApiProperty.getSeguranca().getAuthServerUrl();
}
response.setStatus(FOUND);
response.sendRedirect(returnTo);
}));
return http.formLogin(Customizer.withDefaults()).build();// I want disable this config and use my login form in front-en
}
I have a question about this:
I my login page what endpoint I need to send a user credentials for spring app ? '/login', 'oauth2/login' and how params I need to use in this request?
I use spring-authorization-server in 0.3.1 version

SSO/Oauth login on same application, Login based on UrL

I have spring MVC application and I am trying to register different SSO login on same application. For example if url is (admin.abc.com), It should login from microsoft SSO and if the url is abc.com it should redirect to google login.
Here is my code but when I run the code both sso open with giving me the option to choose.
Is there any way I can set sso login based on domain instead of select option.
#Autowired
ClientRegistrationRepository regRepository;
#Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(Arrays.asList(msClientRegistration(), googleSSOClientRegistration()));
}
and the configuration for antmatcher is like this
#Override
protected void configure(final HttpSecurity http)
throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/login.htm").authenticated()
.antMatchers("/**")
.permitAll().anyRequest()
.authenticated().and().logout()
.logoutSuccessHandler(oauthLogoutSuccessHandler())
.invalidateHttpSession(true)
.logoutUrl("/logout")
.and().oauth2Login()
.failureHandler(new CustomAuthenticationFailureHandler())
.authorizationEndpoint()
.authorizationRequestResolver(
new CustomAuthorizationRequestResolver(regRepository, "/oauth2/authorization"))
.and().tokenEndpoint()
.accessTokenResponseClient(authorizationCodeTokenResponseClient())
.and().and().headers()
.frameOptions()
.sameOrigin().and().csrf()
.disable();
}
How to add antMatcher configuration based on domain url? google sso for abc.com and admin.abc.com for microsoft login with OAuth2.
Instead of having this I want to redirect base on url's.. either Google login or Microsoft.

SpringBoot OAuth2 custom login page

I am able to integrate Zuul server or Spring Cloud gateway with Ping Open ID service.
The basic setup works well.
Now, due to the multi-tenant nature of our platform , I need to customize the default login page so I can provide branding capabilities .
I have tried to override the default OAuth2 login page by overriding the WebSecurityConfigurerAdapter as follows :
.authorizeRequests()
.antMatchers("/login").permitAll().and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.oauth2Login(oauth2 -> oauth2.loginPage("/login")) ;
and on the Cloud Gateway ( using Webflux ) as follows
#Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.oauth2Login(withDefaults()).exceptionHandling().authenticationEntryPoint(new RedirectServerAuthenticationEntryPoint("/login")).and()
.build();
None of these methods work .
The "/login" is a GetMapping controller that attempts to render a simple HTML page with user and password fields.
Any help is appreciated.
thanks

Spring Security with filters permitAll not working

I've got this security config:
#Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(
new JwtLoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(
new JwtAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
http.csrf().disable()
.authorizeRequests().antMatchers("/", "/register").permitAll()
.and()
.authorizeRequests().anyRequest().authenticated();
}
The two filters are doing authentication work: loginFilter checks credentials in the post body and then add cookie to the response. The authenticationFilter checks the auth cookie.
However, permitAll does not let the root route and "/register" route pass (aka. still going through the authenticationFilter, which I thought permitAll would let these routes pass the filters)
What's wrong?
permitAll() does not ignore filters. It simply grants access regardless of whether or not an Authentication is present in a request's security context after all filters have been processed.
You should check your filters and any AuthenticationProvider implementations that they use to to ensure that they are not breaking the execution flow of Spring Security by throwing unchecked/uncaught exceptions or expressly sending a response on a failed authentication.

Resources