Spring Boot + Spring Security + Thymeleaf 举例

本文以Spring Boot Thymeleaf为例,用Spring Security 保护 /admin 和 /user 页面

本例涉及的技术:

1. Spring Boot 1.5.6.REALEASE

2. Spring 4.3.8.REALEASE

3. Spring Security 4.2.2

4. Thymeleaf 2.2.5.REALEASE

5. Tomcat embed 8.5.14

6. Maven 3

7. Java 8

1. 项目目录结构

Spring Boot + Spring Security + Thymeleaf 举例_第1张图片

2. 项目依赖 pom.xml


  4.0.0

  org.thinkingingis
  spring-boot-security
  0.0.1-SNAPSHOT
  jar

  spring-boot-security
  http://maven.apache.org

  
  	org.springframework.boot
    spring-boot-starter-parent
    1.5.6.RELEASE
     
  

  
    UTF-8
    1.8
  
  
  
  	    
        
            org.springframework.boot
            spring-boot-starter-security
        
		
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.thymeleaf.extras
            thymeleaf-extras-springsecurity4
        
         
        
            org.springframework.boot
            spring-boot-devtools
            true
        
        
            org.webjars
            bootstrap
            3.3.7
        
  
  
  	
  		   	
            
                org.springframework.boot
                spring-boot-maven-plugin
            
  	
  



3. Spring Security

3.1 继承自WebSecurityConfigurerAdapter 同时在configure方法中定义了安全角色

对于admin(管理员)角色来说:

a. 可以访问/admin.html页面

b. 不能访问/user.html页面,并重定向到403页面

对于user(用户)角色来说:

a.可以访问/user.html页面

b.不能访问/admin.html页面,并重定向到403页面

SpringSecurityConfig.java

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	private AccessDeniedHandler accessDeniedHandler;
	
	protected void configure(HttpSecurity http) throws Exception{
		http.csrf().disable()
				.authorizeRequests()
					.antMatchers("/", "/home", "/about").permitAll()
					.antMatchers("/admin/**").hasAnyRole("ADMIN")
					.antMatchers("/user/**").hasAnyRole("USER")
					.anyRequest().authenticated()
				.and()
				.formLogin()
					.loginPage("/login")
					.permitAll()
					.and()
				.logout()
					.permitAll()
					.and()
				.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
	}
	
	//create two users admin and user
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
		auth.inMemoryAuthentication()
				.withUser("user").password("password").roles("USER")
				.and()
				.withUser("admin").password("password").roles("ADMIN");
	}
	
}
3.2 定义403无权限访问的处理,重定向到/403页面

MyAccessDeniedHandler.java

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
	
	private static Logger logger = LoggerFactory.getLogger(MyAccessDeniedHandler.class);
	
	@Override
	public void handle( HttpServletRequest httpServletRequest, 
					    HttpServletResponse httpServletResponse, 
					    AccessDeniedException e)
			throws IOException, ServletException {
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		
		if(auth != null) {
			logger.info("User '" + auth.getName() + "' attempted to access the protected URL: " + httpServletRequest.getRequestURI());
		}
		
		httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");
	}

}

4. Spring Boot

4.1 DefaultController.java 

定义http请求和视图名

@Controller
public class DefaultController {
    
	@GetMapping("/")
    public String index() {
        return "/home";
    }

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

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

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

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

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

    @GetMapping("/403")
    public String error403() {
        return "/error/403";
    }
}

4.2 Spring Boot的启动程序

SpringBootWebApplication.java

@SpringBootApplication
public class SpringBootWebApplication {
	public static void main(String[] args) throws Exception {
		SpringApplication.run(SpringBootWebApplication.class, args);
	}

}

5.Thymeleaf及静态资源

对于 thymeleaf 文件,均放到 src/main/resources/templates/目录下

header.html



    
footer.html





© 2017 ThinkingInGIS | Logged user: | Roles: | 登出
home.html



    Spring Boot Thymeleaf + Spring Security
    
    
    
   	


admin.html




    
    



GORGEOUS! 管理员页面 (受 Spring Security 保护, 需要管理员权限)

Hello [[${#httpServletRequest.remoteUser}]]!

user.html




    
    



普通用户页面 (受 Spring Security 保护, 需要用户权限)

Hello [[${#httpServletRequest.remoteUser}]]!

about.html



    
    



游客页面 无需登录

login.html




    
    


登录

Invalid username and password.
You have been logged out.
403.html




    	
    403
    
    


403 - 没有访问权限

Hello '[[${#httpServletRequest.remoteUser}]]', 你没有权限访问此页面.
6.启动程序

6.1 /admin 下面的需要用admin用户登录才能访问

6.2 启动程序,访问 http://localhost:8080/

Spring Boot + Spring Security + Thymeleaf 举例_第2张图片

6.3 访问http://localhost:8080/admin 会被重定向到 http://localhost:8080/login

Spring Boot + Spring Security + Thymeleaf 举例_第3张图片

6.4 当输入无效的用户名和密码后...

Spring Boot + Spring Security + Thymeleaf 举例_第4张图片

6.5 用户名输入admin  密码输入 password 登录,页面会进入到 http://localhost:8080/admin

Spring Boot + Spring Security + Thymeleaf 举例_第5张图片

6.6 输入http://localhost:8080/user 会被重定向到 http://localhost:8080/403 最下面显示了登录的角色及用户名

Spring Boot + Spring Security + Thymeleaf 举例_第6张图片

6.7 点击 登出 会重定向到http://localhost:8080/login?logout

Spring Boot + Spring Security + Thymeleaf 举例_第7张图片

最后,自己试试 用 'user' 访问admin页面可看会有上面结果吧。

源码地址:https://github.com/ThinkingInGIS/spring-boot-security.git

至此,一个简单的spring boot + thymeleaf + spring security 程序 就搭建好了。
(如遇到问题,请留言给作者,以便共同探讨gis知识。[email protected])
更多干货 欢迎关注微信公众号: ThinkingInGIS

Spring Boot + Spring Security + Thymeleaf 举例_第8张图片

如果觉得本文对你有帮助,是可以赞赏作者的哦

Spring Boot + Spring Security + Thymeleaf 举例_第9张图片

你可能感兴趣的:(spring,boot)