Secure a ZK Application with Spring Security"

From Documentation
Line 51: Line 51:
 
= Web Security Configuration =
 
= Web Security Configuration =
  
<source lang='java' high='7, 12, 14'>
+
<source lang='java' high='11, 13, 18,19'>
 
@Configuration
 
@Configuration
 
@EnableWebSecurity
 
@EnableWebSecurity
 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 +
    public static final String ZUL_FILES = "/zkau/web/**/*.zul";
 +
    public static final String[] ZK_RESOURCES = {"/zkau/web/**/js/**", "/zkau/web/**/zul/css/**", "/zkau/web/**/img/**"};
 +
    // allow desktop cleanup after logout or when reloading login page
 +
    public static final String REMOVE_DESKTOP_REGEX = "/zkau\\?dtid=.*&cmd_0=rmDesktop&.*";
 +
 
     @Override
 
     @Override
 
     protected void configure(HttpSecurity http) throws Exception {
 
     protected void configure(HttpSecurity http) throws Exception {
       
 
 
         http.csrf().disable();
 
         http.csrf().disable();
 
         http.authorizeRequests()
 
         http.authorizeRequests()
             .antMatchers("/zkau/web/**/js/**","/zkau/web/**/zul/css/**","/zkau/web/**/img/**")
+
             .antMatchers(ZUL_FILES).denyAll() // block direct access to zul files
             .permitAll()
+
            .antMatchers(HttpMethod.GET, ZK_RESOURCES).permitAll() // allow zk resources
            // block direct access to class path web resources
+
             .regexMatchers(HttpMethod.GET, REMOVE_DESKTOP_REGEX).permitAll() // allow desktop cleanup
             .antMatchers("/zkau/web/**/**.zul").denyAll()
+
             .requestMatchers(req -> "rmDesktop".equals(req.getParameter("cmd_0"))).permitAll() // allow desktop cleanup from ZATS
 
             .mvcMatchers("/","/login","/logout").permitAll()
 
             .mvcMatchers("/","/login","/logout").permitAll()
 
             .mvcMatchers("/secure").hasRole("USER")
 
             .mvcMatchers("/secure").hasRole("USER")
Line 89: Line 93:
 
</source>
 
</source>
 
* Line 7: We need to disable spring CSRF to make ZK AU pass security filter. But don't worry. [[ ZK%20Developer's%20Reference/Security%20Tips/Cross-site%20Request%20Forgery | ZK already has its own CSRF mechanism]].
 
* Line 7: We need to disable spring CSRF to make ZK AU pass security filter. But don't worry. [[ ZK%20Developer's%20Reference/Security%20Tips/Cross-site%20Request%20Forgery | ZK already has its own CSRF mechanism]].
* Line 12: This line blocks the public access to [[ZK_Developer%27s_Reference/UI_Composing/ZUML/Include_a_Page#Classpath_Web_Resource_Path | ZK class path web resource folder]].
+
* Line 13: This line blocks the public access to [[ZK_Developer%27s_Reference/UI_Composing/ZUML/Include_a_Page#Classpath_Web_Resource_Path | ZK class path web resource folder]].
* Line 14: Assume we want all pages under <tt>/secure</tt> are protected and require an authentication.
+
* Line 18-19: Assume we want all pages under <tt>/secure</tt> are protected and require an authentication.
  
 
= Login Page=
 
= Login Page=

Revision as of 08:45, 13 September 2018

Secure a ZK Application with Spring Security



Secure Your Application in Spring's Way

Spring Security is a widely-adopted framework. It can also work with ZK without problems. This doesn't even need zkspring-security. This page will show you how to do it. We assume you know the basic of Spring Boot and Spring Security. (You can read a Spring Security guide: Securing a Web Application ) So here we just mention those configurations specific to ZK framework.

ZK Spring Boot Starter

Spring encourages users to start with Spring Boot. So Please include zk spring boot starter, and it will automatically configure for you with most commonly-used settings.

Spring Boot Starter Security

Follow Securing a Web Application, we add the following elements:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>${springboot.version}</version>
        </dependency>

Spring Controller

For simplicity, we just register 2 URL mapping:

  • /login: login page
  • /secure/{page}: all secure pages
@SpringBootApplication
@Controller
public class Application {

    public static void main(String[] args) throws Throwable {
        SpringApplication.run(Application.class, args);
    }

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

    @GetMapping("/secure/{page}")
    public String secure(@PathVariable String page) {
        return "secure/" + page;
    }
}

Then put the corresponding zul under web/zul folder.

Zkspring-zul-path.png

Web Security Configuration

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    public static final String ZUL_FILES = "/zkau/web/**/*.zul";
    public static final String[] ZK_RESOURCES = {"/zkau/web/**/js/**", "/zkau/web/**/zul/css/**", "/zkau/web/**/img/**"};
    // allow desktop cleanup after logout or when reloading login page
    public static final String REMOVE_DESKTOP_REGEX = "/zkau\\?dtid=.*&cmd_0=rmDesktop&.*";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
            .antMatchers(ZUL_FILES).denyAll() // block direct access to zul files
            .antMatchers(HttpMethod.GET, ZK_RESOURCES).permitAll() // allow zk resources
            .regexMatchers(HttpMethod.GET, REMOVE_DESKTOP_REGEX).permitAll() // allow desktop cleanup
            .requestMatchers(req -> "rmDesktop".equals(req.getParameter("cmd_0"))).permitAll() // allow desktop cleanup from ZATS
            .mvcMatchers("/","/login","/logout").permitAll()
            .mvcMatchers("/secure").hasRole("USER")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").defaultSuccessUrl("/secure/main")
            .and()
            .logout().logoutUrl("/logout").logoutSuccessUrl("/");
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("user")
                        .password("password")
                        .roles("USER")
                        .build();

        return new InMemoryUserDetailsManager(user);
    }
}

Login Page

No matter how you design a login page, remember to enclose it with a <form> and the login URL you specify in web security config.

    <n:form action="/login" method="POST">
        <grid width="450px">
            ...
                <row spans="2" align="right">
                    <hlayout>
                    <button type="reset" label="Reset" /> <button type="submit" label="Submit" />
                    </hlayout>
                </row>
          ...
        </grid>
    </n:form>

Download Demo Project

Version History

Last Update : 2018/09/13


Version Date Content
     



Last Update : 2018/09/13

Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.