简体   繁体   中英

Custom login page in Spring Security 5 using oauth2 returns null

I am developing custom login page in Spring Security 5 using oauth2 . So I have customized settings:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login().loginPage("/login/oauth2").permitAll();
    }

and creating controller with @RequestMapping("/login/oauth2") :

@GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/login/oauth2")
    public String login(Model model, OAuth2AuthenticationToken authentication) {
        return "login";
    }

The login.html page is a regular form which redirect to login method from controller:

 <h1>Logowanie</h1>
<a>ZALOGUJ</a>
<a class="btn" href="/login/oauth2/code/google">Login</a>

With this configuration OAuth2AuthenticationToken authentication is null and therefore authentication can't be applied. With default Spring Security 5 configuration everything works fine. The example on which I based is described here: https://docs.spring.io/spring-security/site/docs/5.0.0.RELEASE/reference/htmlsingle/#oauth2login-advanced-login-page ; section 31.1 OAuth 2.0 Login Page .

In my app to work I had to create my custom WebMvc configuration:

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}

Then in WebSecurityConfig:

 @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and().formLogin()
                .loginPage("/login")
                .permitAll()
                .and().csrf().disable()
                .logout().permitAll();
    }

I think in this case You don't need custom controller.

I wrote a blog post about silent token refresh in implicit flow, but there You will find full working app with custom login page:

https://regulargeek.blogspot.com/2018/05/angular-5-springboot-2-oauth2-and.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM