Java Spring Bootサービスにおける認証/認可、検証、CSRF、シークレット、ヘッダー、レート制限、依存関係セキュリティのためのSpring Securityベストプラクティス。
認証の追加、入力処理、エンドポイント作成、シークレットの扱いの際に使用します。
httpOnly, Secure, SameSite=Strict クッキーを使用するOncePerRequestFilter またはリソースサーバーでトークンを検証する@Component
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtService jwtService;
public JwtAuthFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null && header.startsWith("Bearer ")) {
String token = header.substring(7);
Authentication auth = jwtService.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
chain.doFilter(request, response);
}
}
@EnableMethodSecurity@PreAuthorize("hasRole('ADMIN')") または @PreAuthorize("@authz.canEdit(#id)") を使用する@Valid を使用したBean Validationを使用する@NotBlank, @Email, @Size, カスタムバリデータ:param バインディングを使用; 文字列を連結しないhttp
.csrf(csrf -> csrf.disable())
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
application.yml を資格情報なしに保つ; プレースホルダーを使用するhttp
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'"))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
.xssProtection(Customizer.withDefaults())
.referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));
覚えておくこと: デフォルトで拒否し、入力を検証し、最小権限で、まず設定によるセキュリティを確保する。