2017 年 5 月 29 日,作者:Sébastien Blanc
./standalone.sh(bat)然後開啟瀏覽器並前往 https://127.0.0.1:8080/auth。由於這是伺服器第一次執行,您必須建立一個管理使用者,所以讓我們建立一個使用者名稱為 admin、密碼為 admin 的管理使用者
<html> <head> <title>My awesome landing page</title> </head> <body> <h2>Landing page</h2> <a href="/products">My products</a> </body> </html>現在我們需要一個控制器
@Controller class ProductController { @Autowired ProductService productService; @GetMapping(path = "/products") public String getProducts(Model model){ model.addAttribute("products", productService.getProducts()); return "products"; } @GetMapping(path = "/logout") public String logout(HttpServletRequest request) throws ServletException { request.logout(); return "/"; } }如您所見,它很簡單;我們為產品頁面定義一個對應,為登出動作定義一個對應。您還會注意到我們正在呼叫一個「ProductService」,它將傳回一個字串清單,這些字串將放入我們的 Spring MVC Model 物件中,所以讓我們建立該服務
@Component class ProductService { public List<String> getProducts() { return Arrays.asList("iPad","iPod","iPhone"); } }我們也需要建立 product.ftl 範本,在「src/resources/templates」中建立此檔案
<#import "/spring.ftl" as spring> <html> <h2>My products</h2> <ul> <#list products as product> <li>$amp{product}</li> </#list> </ul> <p> <a href="/logout">Logout</a> </p> </html>在這裡,我們只是簡單地疊代我們的 Spring MVC Model 物件中的產品清單,並新增一個從應用程式登出的連結。剩下的就是將一些 keycloak 屬性新增到我們的 application.properties 中。
keycloak.auth-server-url=https://127.0.0.1:8080/auth keycloak.realm=springboot keycloak.public-client=true keycloak.resource=product-app然後我們需要定義一些安全性限制,就像您在 web.xml 中使用 Java EE 應用程式一樣
keycloak.security-constraints[0].authRoles[0]=user keycloak.security-constraints[0].securityCollections[0].patterns[0]=/products/*在這裡,我們只是簡單地定義對 /products/* 的每個請求都應該由經過驗證的使用者執行,而且此使用者應該具有角色「user」。最後一個屬性是確保我們的應用程式將在連接埠 8081 上執行
server.port=8081我們都設定好了,我們可以執行我們的應用程式了!您有幾個選項可以執行您的 Spring Boot 應用程式,使用 Maven,您可以簡單地執行
mvn clean spring-boot:run現在瀏覽到「https://127.0.0.1:8080」,您應該會看到登陸頁面,按一下「產品」連結,您將被重新導向到 Keycloak 登入頁面
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
@Configuration @EnableWebSecurity @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { /** * Registers the KeycloakAuthenticationProvider with the authentication manager. */ @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper()); auth.authenticationProvider(keycloakAuthenticationProvider); } @Bean public KeycloakConfigResolver KeycloakConfigResolver() { return new KeycloakSpringBootConfigResolver(); } /** * Defines the session authentication strategy. */ @Bean @Override protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); } @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); http .authorizeRequests() .antMatchers("/products*").hasRole("user") .anyRequest().permitAll(); } }讓我們仔細看看最重要的幾個方法
keycloak.principal-attribute=preferred_username現在我們甚至可以在我們的控制器方法中注入 principal,並將使用者名稱放入 Spring MVC 模型中
@GetMapping(path = "/products") public String getProducts(Principal principal, Model model){ model.addAttribute("principal",principal); model.addAttribute("products", productService.getProducts()); return "products"; }最後,我們更新 product.ftl 範本以列印出使用者名稱
<#import "/spring.ftl" as spring> <html> <h2>Hello $amp{principal.getName()}</h2> <ul> <#list products as product> <li>$amp{product}</li> </#list> </ul> <p> <a href="/logout">Logout</a> </p> </html>重新啟動您的應用程式,再次驗證,它應該仍然可以運作,而且您也應該能夠在產品頁面上看到列印的使用者名稱