10 Mart 2021 Çarşamba

SpringWebFlux Security

Giriş
Şu satırı dahil ederiz
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
Örnek
Şöyle yaparız
@EnableWebFluxSecurity
public class HelloWebFluxSecurityConfig {
  @Bean
  public MapReactiveUserDetailsService userDetailsService() {
    UserDetails user = User.withDefaultPasswordEncoder()
      .username("user")
      .password("user")
      .roles("USER")
      .build();
    return new MapReactiveUserDetailsService(user);
  }
}
Örnek
Şöyle yaparız
@Component
public class AuthenticationManager implements ReactiveAuthenticationManager {

  @Autowired
  private JWTUtil jwtUtil;

  @Override
  public Mono<Authentication> authenticate(Authentication authentication) {

    String authToken = authentication.getCredentials().toString();
    return Mono.just(authToken)
               .map(token -> jwtUtil.validateToken(token))
               .onErrorResume(e -> Mono.empty())
               .flatMap(isValid -> jwtUtil.getAllClaimsFromToken(authToken))
               .map(claims -> new UsernamePasswordAuthenticationToken(
                 claims.getSubject(), 
                 null, 
                 Collections.singletonList(new SimpleGrantedAuthority(
                   claims.get(KEY_ROLE).toString()))));
    }
}


Hiç yorum yok:

Yorum Gönder