spring-boot整合spring-security和thymeleaf

在controler中獲取用戶名信息

Spring會自動注入Principal,經過principal能夠能夠獲取到登陸用戶的用戶名:html

@Controller
public class MockController {
  @GetMapping(value="/mock")
  public String mock(ModelMap model, Principal principal ) {
      String name = principal.getName(); //get logged in username
      return "mock";

  }
}

在template中獲取登陸用戶的信息

這裏咱們使用官網推薦的thymeleaf-extras-springsecurityREADME.md給出了詳細的教程,可是都是基於Spring-MVC的,在和Spring-Boot整合的時候還有一些問題。java

好比StackOverflow中這個問題上面提到的Spring-Boot如今的最新版的Thymeleaf Extras for Spring Security 4並不支持3.x.x,所以只能使用2.x.x。p.s: Spring-Boot1.5.3默認加載的版本是~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]git

stackoverflow上面的一些答案以及README.md中提到要註冊SpringTemplateEngine,在如今的最新Spring-Boot1.5.3下面這段代碼這是沒有必要的,Spring-Boot會實現自動注入。github

@Bean
    public SpringTemplateEngine templateEngine(TemplateResolver templateResolver, SpringSecurityDialect sec) {
        final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        templateEngine.addDialect(sec); // Enable use of "sec"
        return templateEngine;
    }

p.s: 若是使用intellij-idea的話,參考官網文檔能夠在Add Framework中添加thymeleaf支持,以實現自動補全。spring

相關文章
相關標籤/搜索