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オブジェクトにある製品のリストを反復処理し、アプリケーションからログアウトするためのリンクを追加します。残っているのは、application.propertiesにいくつかのkeycloakプロパティを追加することだけです。
keycloak.auth-server-url=https://127.0.0.1:8080/auth keycloak.realm=springboot keycloak.public-client=true keycloak.resource=product-app次に、Java EEアプリでweb.xmlで行うように、いくつかのセキュリティ制約を定義する必要があります。
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」を参照すると、ランディングページが表示されます。「products」リンクをクリックすると、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これで、プリンシパルをコントローラーメソッドに注入し、ユーザー名を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>アプリを再起動し、再度認証すると、引き続き機能し、製品ページにユーザー名が表示されるはずです。