@EnableWebSecuritypublic class SecurityConfig { private final JwtTokenFilter jwtTokenFilter; public SecurityConfig(JwtTokenFilter jwtTokenFilter) { this.jwtTokenFilter = jwtTokenFilter; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // enable CORS and disable CSRF http = http.cors(corsConfig -> corsConfig .configurationSource(configurationSource()) ).csrf().disable(); // set session management to stateless http = http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and(); // set permissions on endpoints http.authorizeHttpRequests(authorize -> authorize .mvcMatchers("/api/redirect-url", "/api/signin").permitAll() .mvcMatchers("/api/**").authenticated() ); // set unauthorized requests exception handler http = http .exceptionHandling() .authenticationEntryPoint( (request, response, ex) -> ResponseUtils.fail(response, "unauthorized") ) .and(); // add JWT token filter http.addFilterBefore( jwtTokenFilter, UsernamePasswordAuthenticationFilter.class ); return http.build(); } // ...}
Add a simple JWT filter to intercept requests that require token verification.
@Componentpublic class JwtTokenFilter extends OncePerRequestFilter { private final Hanzo IAMAuthService iamAuthService; public JwtTokenFilter(Hanzo IAMAuthService iamAuthService) { this.iamAuthService = iamAuthService; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { // get authorization header and validate final String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (!StringUtils.hasText(header) || !header.startsWith("Bearer ")) { chain.doFilter(request, response); return; } // get jwt token and validate final String token = header.split(" ")[1].trim(); // get user identity and set it on the spring security context UserDetails userDetails = null; try { Hanzo IAMUser iamUser = iamAuthService.parseJwtToken(token); userDetails = new CustomUserDetails(iamUser); } catch (Hanzo IAMAuthException exception) { logger.error("iam auth exception", exception); chain.doFilter(request, response); return; } UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, AuthorityUtils.createAuthorityList("ROLE_iam") ); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails(request) ); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(request, response); }}
When the user accesses the interface requiring authentication, JwtTokenFilter will obtain the token from the request header Authorization and verify it.
Define a Controller to handle when the user logs in to Hanzo IAM. After the user logs in, they will be redirected to the server and carry the code and state. The server then needs to verify the user's identity from Hanzo IAM and obtain the token through these two parameters.