Spring Boot + Spring Security + Thymeleaf example

姓名:岳沁

学号:17101223458

转载自:http://www.mkyong.com/spring-boot/spring-boot-spring-security-thymeleaf-example/

【嵌牛导读】:

Spring Boot + Spring Security + Thymeleaf example

【嵌牛鼻子】:thymeleaf

【嵌牛提问】:thymeleaf解析机制是什么?

【嵌牛正文】:

A Spring Boot Thymeleaf example, uses Spring Security to protect path/adminand/user

Technologies used :

Spring Boot 1.5.3.RELEASE

Spring 4.3.8.RELEASE

Spring Security 4.2.2

Thymeleaf 2.1.5.RELEASE

Thymeleaf extras Spring Security4 2.1.3

Tomcat Embed 8.5.14

Maven 3

Java 8

1. Project Directory

2. Project Dependencies

Declaresspring-boot-starter-security, it will get anything you need to develop aSpring Boot + Spring Securityweb application.

pom.xml

4.0.0spring-boot-web-spring-securityjarSpring Boot Web Spring SecuritySpring Boot Web Spring Security Examplehttps://www.mkyong.com1.0org.springframework.bootspring-boot-starter-parent1.5.3.RELEASE1.8org.springframework.bootspring-boot-starter-securityorg.springframework.bootspring-boot-starter-thymeleaforg.thymeleaf.extrasthymeleaf-extras-springsecurity4org.springframework.bootspring-boot-devtoolstrueorg.webjarsbootstrap3.3.7org.springframework.bootspring-boot-maven-plugin

Display project dependencies :

$ mvn dependency:tree[INFO]Scanningforprojects...[INFO][INFO]------------------------------------------------------------------------[INFO]Building Spring Boot Web Spring Security 1.0[INFO]------------------------------------------------------------------------[INFO][INFO]--- maven-dependency-plugin:2.10:tree(default-cli)@ spring-boot-web-spring-security ---[INFO]org.springframework.boot:spring-boot-web-spring-security:jar:1.0[INFO]+- org.springframework.boot:spring-boot-starter-thymeleaf:jar:1.5.3.RELEASE:compile[INFO]|+- org.springframework.boot:spring-boot-starter:jar:1.5.3.RELEASE:compile[INFO]||+- org.springframework.boot:spring-boot-starter-logging:jar:1.5.3.RELEASE:compile[INFO]|||+- ch.qos.logback:logback-classic:jar:1.1.11:compile[INFO]||||\- ch.qos.logback:logback-core:jar:1.1.11:compile[INFO]|||+- org.slf4j:jcl-over-slf4j:jar:1.7.25:compile[INFO]|||+- org.slf4j:jul-to-slf4j:jar:1.7.25:compile[INFO]|||\- org.slf4j:log4j-over-slf4j:jar:1.7.25:compile[INFO]||+- org.springframework:spring-core:jar:4.3.8.RELEASE:compile[INFO]||\- org.yaml:snakeyaml:jar:1.17:runtime[INFO]|+- org.springframework.boot:spring-boot-starter-web:jar:1.5.3.RELEASE:compile[INFO]||+- org.springframework.boot:spring-boot-starter-tomcat:jar:1.5.3.RELEASE:compile[INFO]|||+- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.14:compile[INFO]|||+- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.14:compile[INFO]|||\- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.14:compile[INFO]||+- org.hibernate:hibernate-validator:jar:5.3.5.Final:compile[INFO]|||+- javax.validation:validation-api:jar:1.1.0.Final:compile[INFO]|||+- org.jboss.logging:jboss-logging:jar:3.3.1.Final:compile[INFO]|||\- com.fasterxml:classmate:jar:1.3.3:compile[INFO]||+- com.fasterxml.jackson.core:jackson-databind:jar:2.8.8:compile[INFO]|||+- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile[INFO]|||\- com.fasterxml.jackson.core:jackson-core:jar:2.8.8:compile[INFO]||+- org.springframework:spring-web:jar:4.3.8.RELEASE:compile[INFO]||\- org.springframework:spring-webmvc:jar:4.3.8.RELEASE:compile[INFO]|+- org.thymeleaf:thymeleaf-spring4:jar:2.1.5.RELEASE:compile[INFO]||\- org.thymeleaf:thymeleaf:jar:2.1.5.RELEASE:compile[INFO]||+- ognl:ognl:jar:3.0.8:compile[INFO]||+- org.javassist:javassist:jar:3.21.0-GA:compile[INFO]||\- org.unbescape:unbescape:jar:1.1.0.RELEASE:compile[INFO]|\- nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:jar:1.4.0:compile[INFO]|\- org.codehaus.groovy:groovy:jar:2.4.10:compile[INFO]+- org.springframework.boot:spring-boot-starter-security:jar:1.5.3.RELEASE:compile[INFO]|+- org.springframework:spring-aop:jar:4.3.8.RELEASE:compile[INFO]||\- org.springframework:spring-beans:jar:4.3.8.RELEASE:compile[INFO]|+- org.springframework.security:spring-security-config:jar:4.2.2.RELEASE:compile[INFO]||+- org.springframework.security:spring-security-core:jar:4.2.2.RELEASE:compile[INFO]||\- org.springframework:spring-context:jar:4.3.8.RELEASE:compile[INFO]|\- org.springframework.security:spring-security-web:jar:4.2.2.RELEASE:compile[INFO]|\- org.springframework:spring-expression:jar:4.3.8.RELEASE:compile[INFO]+- org.thymeleaf.extras:thymeleaf-extras-springsecurity4:jar:2.1.3.RELEASE:compile[INFO]|\- org.slf4j:slf4j-api:jar:1.7.25:compile[INFO]+- org.springframework.boot:spring-boot-devtools:jar:1.5.3.RELEASE:compile[INFO]|+- org.springframework.boot:spring-boot:jar:1.5.3.RELEASE:compile[INFO]|\- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.3.RELEASE:compile[INFO]\- org.webjars:bootstrap:jar:3.3.7:compile[INFO]\- org.webjars:jquery:jar:1.11.1:compile[INFO]------------------------------------------------------------------------[INFO]BUILD SUCCESS[INFO]------------------------------------------------------------------------[INFO]Total time: 2.072 s[INFO]Finished at: 2017-05-04T10:13:05+08:00[INFO]Final Memory: 19M/309M[INFO]------------------------------------------------------------------------

3. Spring Security

3.1 ExtendsWebSecurityConfigurerAdapter, and defined the security rules in theconfiguremethod.

For user “admin” :

Able to access/adminpage

Unable to access/userpage, redirect to 403 access denied page.

For user “user” :

able to access/userpage

unable to access/adminpage, redirect to 403 access denied page.

SpringSecurityConfig.java

packagecom.mkyong.config;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Configuration;importorg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;importorg.springframework.security.web.access.AccessDeniedHandler;@ConfigurationpublicclassSpringSecurityConfigextendsWebSecurityConfigurerAdapter{@AutowiredprivateAccessDeniedHandler accessDeniedHandler;// roles admin allow to access /admin/**// roles user allow to access /user/**// custom 403 access denied handler@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{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@AutowiredpublicvoidconfigureGlobal(AuthenticationManagerBuilder auth)throwsException{auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password").roles("ADMIN");}}

3.2 Custom 403 Access denied handler, logs the request and redirect to/403

WelcomeController.java

packagecom.mkyong.error;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.security.access.AccessDeniedException;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.context.SecurityContextHolder;importorg.springframework.security.web.access.AccessDeniedHandler;importorg.springframework.stereotype.Component;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;// handle 403 page@ComponentpublicclassMyAccessDeniedHandlerimplementsAccessDeniedHandler{privatestaticLogger logger=LoggerFactory.getLogger(MyAccessDeniedHandler.class);@Overridepublicvoidhandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,AccessDeniedException e)throwsIOException,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 A controller class, to define the http request and view name.

DefaultController.java

packagecom.mkyong.controller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.GetMapping;@ControllerpublicclassDefaultController{@GetMapping("/")publicStringhome1(){return"/home";}@GetMapping("/home")publicStringhome(){return"/home";}@GetMapping("/admin")publicStringadmin(){return"/admin";}@GetMapping("/user")publicStringuser(){return"/user";}@GetMapping("/about")publicStringabout(){return"/about";}@GetMapping("/login")publicStringlogin(){return"/login";}@GetMapping("/403")publicStringerror403(){return"/error/403";}}

4.2 Start Spring Boot application.

DefaultController.java

packagecom.mkyong;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassSpringBootWebApplication{publicstaticvoidmain(String[]args)throwsException{SpringApplication.run(SpringBootWebApplication.class,args);}}

5. Thymeleaf + Resources + Static files

5.1 For Thymeleaf files, put insrc/main/resources/templates/folder.

5.2 Thymeleaf fragments, for template layout – header.

src/main/resources/templates/fragments/header.html

Spring BootHome

5.3 Thymeleaf fragments, for template layout – footer. Review thesectag, it is a useful tag to display the Spring Security stuff, refer to thisThymeleaf extra Spring Securityfor detail.

src/main/resources/templates/fragments/footer.html

© 2017 mkyong.com| Logged user:|                Roles:|Sign Out

5.4 List of the Thymeleaf files, nothing special, self-explanatory.

home ~

src/main/resources/templates/home.html

Spring Boot Thymeleaf + Spring Security

Spring Boot Web Thymeleaf + Spring Security

1. VisitAdmin page (Spring Security protected, Need Admin Role)

2. VisitUser page (Spring Security protected, Need User Role)

3. VisitNormal page

admin ~

src/main/resources/templates/admin.html

Admin page (Spring Security protected)

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

user ~

src/main/resources/templates/user.html

User page (Spring Security protected)

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

about ~

src/main/resources/templates/about.html

Normal page (No need login)

login ~

src/main/resources/templates/login.html

Spring Security Example

Please Sign In

Invalid username and password.You have been logged out.

403 ~

src/main/resources/templates/error/403.html

403 - Access is denied

Hello '[[${#httpServletRequest.remoteUser}]]',                you do not have permission to access this page.

5.5 For static files like CSS or Javascript, put in/src/main/resources/static/

/src/main/resources/static/css/main.css

h1{color:#0000FF;}h2{color:#FF0000;}footer{margin-top:60px;}

Note

Read thisSpring Boot Serving static contentto understand the resource mapping.

6. Demo

6.1 Start the Spring Boot web app. This/admin/**is protected, you need login as admin to access it.

Terminal

$ mvn spring-boot:run//...

6.2 Accesshttp://localhost:8080

6.3 Accesshttp://localhost:8080/admin, redirect tohttp://localhost:8080/login

6.4 Invalid username or passwordhttp://localhost:8080/login

6.5 Login successful, redirect back to admin pagehttp://localhost:8080/admin, review the footer section, the user info is displayed.

6.6 Accesshttp://localhost:8080/user, redirect tohttp://localhost:8080/403

6.7 Clicks on the sign out link in the footer, redirect tohttp://localhost:8080/login?logout

Done. Try login with another username “user” and access the admin page.

Download Source Code

Download it –spring-boot-spring-security-thymeleaf.zip(15 KB)

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,905评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,140评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,791评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,483评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,476评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,516评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,905评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,560评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,778评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,557评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,635评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,338评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,925评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,898评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,142评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,818评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,347评论 2 342

推荐阅读更多精彩内容