首页 > 解决方案 > 是否可以使用jsp登录表单作为spring security的自定义登录表单

问题描述

我有一个 Spring Boot 项目,所有视图都是 JSP 页面: 是否可以使用 jsp 表单作为自定义登录页面?

标签: javaspring-bootjspspring-security

解决方案


您可以在 Spring security 中创建您自己的自定义登录页面

  1. 创建自定义页面。例如 - 在名为 login.jsp 的视图中的 auth 文件夹中创建您的自定义登录

  2. 在 Spring 安全配置文件中

     @Configuration
     public class SecurityConfiguration extends WebMvcConfigurerAdapter {
        private static final String LOGIN_URL = "/";
        private static final String LOGOUT_URL = "/logout";
    
        /**
        * Associate the specified URL with the view corresponding to that URL (the same as {@ code mvc: view - controller}).
        * <p>
        * In this class implementation, we only associate the login screen URL with the login screen view.
        * You won't be able to add model attributes through the controller registry. Instead, configure your InternalResourceViewResolver to expose beans to the JSP
        *(through request attributes, which is equivalent to what happens to model attributes). 
        *
        * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#addViewControllers(org.springframework.web.servlet.config.annotation.ViewControllerRegistry)
        */
        @Override
            public void addViewControllers(final ViewControllerRegistry registry) {
                registry.addViewController(LOGIN_URL).setViewName("auth/login");
        }
    
    
        @Configuration
        @Order(SecurityProperties.BASIC_AUTH_ORDER)
        protected static class FormSecurity extends WebSecurityConfigurerAdapter {
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
    
                http.formLogin()
                    .loginPage(LOGIN_URL);
    
                http.logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher(LOGOUT_URL))
                    .logoutSuccessUrl(LOGIN_URL)
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true)
                    .clearAuthentication(true);
                }
            }
       }    
    

推荐阅读