How to use Spring Security to custom login page?

前端 未结 3 1515
夕颜
夕颜 2021-01-02 14:16

I am using Spring Security to my application and here is the security part which authenticates the user but the login page is given by Spring Security:



        
3条回答
  •  自闭症患者
    2021-01-02 15:08

    Just want to pinpoint a few moments that were not clarified here.

    1. First of all, .loginPage("/login.html") won't do the trick (it didn't in my case anyway). What is in quotes here is an URL path that will be searched for in your controller. Here is the snippet from my security config file:

       .formLogin().loginPage("/login")
       .loginProcessingUrl("/authentication").permitAll();
      

    Here I wrote "/login". So now in your controller define that the /login path should point to your login.html page.

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

    Only then it should redirect to the required view page. I usually place view pages under the /webapp/WEB-INF/view folder.
    P.S. I hope you configured your ViewResolver bean right, cos otherwise it won't work :)

    1. And one more thing. I see you wanna use some CSS for the page. To enable CSS and other static resources for your custom login page, you should add this line

    .antMatchers("/resources/**").permitAll()

    So, in the end it will be like that (very short and creepy version, but your custom login should work):

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
    
            .formLogin().loginPage("/login")
            .loginProcessingUrl("/authentication").permitAll();
    }
    

    FYI, place your resources under /webapp/resources/. Also, you should configure your resource handler in your spring configuration file.

    Here is also a nice link to wrap your head around it:

    https://docs.spring.io/spring-security/site/docs/current/guides/html5/form-javaconfig.html#grant-access-to-remaining-resources

提交回复
热议问题