Search code examples
springspring-securityspring-security-oauth2spring-oauth2

How does Spring Oauth2 login redirect work?


I've been thrashing around with the Spring Boot Oauth2 tutorial and I can't seem to get a pretty key element working:

https://spring.io/guides/tutorials/spring-boot-oauth2/

I want to run as an authorization server. I've followed the instructions as closely as I can fathom, but when I go to the /oauth/authorize endpoint, all I ever get is a 403 Forbidden response. This actually makes sense to me given the HttpSecurity configuration that the tutorial sets up:

protected void configure(HttpSecurity http) throws Exception {
    http
      .antMatcher("/**")
      .authorizeRequests()
        .antMatchers("/", "/login**", "/webjars/**")
        .permitAll()
      .anyRequest()
        .authenticated()
        .and().logout().logoutSuccessUrl("/").permitAll()
        .and().csrf().csrfTokenRepository(csrfTokenRepository())
        .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
        .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
}

The login page for this tutorial is actually the main index and I definitely don't see anything in the tutorial that would instruct the Oauth system to redirect the login flow there.

I can get it kind of working by adding this:

        .and().formLogin().loginPage("/")

...but before moving forward I really wanted to understand if this is a problem with the tutorial or my implementation of it or something else. What is the mechanism by which the Oauth security system decides what a "login" page is?


Solution

  • The solution was to add the following to the SecurityConfig.configure call:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        AuthenticationEntryPoint aep = new AuthenticationEntryPoint() {
    
            @Override
            public void commence(HttpServletRequest request,
                    HttpServletResponse response,
                    AuthenticationException authException) throws IOException,
                    ServletException {
                response.sendRedirect("/login");
            }
        };
    
        http.exceptionHandling()
                .authenticationEntryPoint(aep)
    

    Which redirects the authentication flow to a specific URL (in this case I am sending it to "/login", but it also worked with "/" or anything else I chose). I have no idea how the tutorial is supposed to do the redirect without explicitly adding this line.