Spring Securityでユーザー情報を取得する
1. 概要
この記事では、retrieve the user details in Spring Securityを実行する方法を説明します。
現在認証されているユーザーは、Springのさまざまなメカニズムを通じて利用できます。まず、最も一般的なソリューションであるプログラムによるアクセスについて説明します。
参考文献:
Spring Securityでログインしたユーザーを追跡する
Spring Securityを使用して構築されたアプリケーションでログインしているユーザーを追跡するためのクイックガイド。
2. Beanでユーザーを取得する
現在認証されているプリンシパルを取得する最も簡単な方法は、SecurityContextHolderへの静的呼び出しを使用することです。
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();
このスニペットの改善点は、アクセスを試みる前に、認証されたユーザーがいるかどうかを最初に確認することです。
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
return currentUserName;
}
もちろん、このような静的呼び出しを行うことには欠点があります。コードのテスト容易性が低下するのは明らかです。 代わりに、この非常に一般的な要件に対する代替ソリューションを検討します。
3. コントローラーでユーザーを取得する
@Controllerアノテーション付きBeanには、追加のオプションがあります。 The principal can be defined directly as a method argumentであり、フレームワークによって正しく解決されます。
@Controller
public class SecurityController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserName(Principal principal) {
return principal.getName();
}
}
または、we can also use the authentication token:
@Controller
public class SecurityController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserName(Authentication authentication) {
return authentication.getName();
}
}
AuthenticationクラスのAPIは非常にオープンであるため、フレームワークは可能な限り柔軟なままです。 このため、the Spring Security principal can only be retrieved as an Object and needs to be cast to the correct UserDetails instance:
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("User has authorities: " + userDetails.getAuthorities());
そして最後に、直接from the HTTP request:
@Controller
public class GetUserWithHTTPServletRequestController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserNameSimple(HttpServletRequest request) {
Principal principal = request.getUserPrincipal();
return principal.getName();
}
}
4. カスタムインターフェイスを介してユーザーを取得する
Springの依存性注入を完全に活用し、@Controller beansだけでなく、あらゆる場所で認証を取得できるようにするには、静的アクセスを単純なファサードの背後に隠す必要があります。
public interface IAuthenticationFacade {
Authentication getAuthentication();
}
@Component
public class AuthenticationFacade implements IAuthenticationFacade {
@Override
public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
}
ファサードは、静的状態を非表示にし、コードを分離して完全にテスト可能に保ちながら、Authenticationオブジェクトを公開します。
@Controller
public class GetUserWithCustomInterfaceController {
@Autowired
private IAuthenticationFacade authenticationFacade;
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserNameSimple() {
Authentication authentication = authenticationFacade.getAuthentication();
return authentication.getName();
}
}
5. JSPでユーザーを取得する
Spring Security Taglibサポートを活用して、現在認証されているプリンシパルcan also be accessed in JSP pages。 まず、ページでタグを定義する必要があります。
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
次に、refer to the principalを実行できます。
authenticated as
6. Thymeleafでユーザーを取得する
Thymeleafは、優れたintegration with the Spring MVCフレームワークを備えた、最新のサーバー側Webテンプレートエンジンです。 Thymeleafエンジンを使用して、ページで現在認証されているプリンシパルにアクセスする方法を見てみましょう。
まず、thymeleaf-spring5とthymeleaf-extras-springsecurity5の依存関係を追加して、ThymeleafをSpringSecurityと統合する必要があります。
org.thymeleaf.extras
thymeleaf-extras-springsecurity5
org.thymeleaf
thymeleaf-spring5
今we can refer to the principal in the HTML page using the sec:authorize attribute:
Authenticated as
7. 結論
この記事では、Springアプリケーションでユーザー情報を取得する方法を示しました。一般的な静的アクセスメカニズムから始めて、プリンシパルを注入するためのいくつかのより良い方法が続きます。
これらの例の実装はthe GitHub projectにあります。これはEclipseベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。 プロジェクトをローカルで実行すると、ホームページのHTMLにアクセスできます。
http://localhost:8080/spring-security-rest-custom/foos/1