Spring cloud как достать currentUser

Пытаюсь создать приложение на микросервисах(новичок). Создал 4 сервиса для первого Hello World: 1.spring-eureke-server 2 spring-eureke-zuul 3.spring-eureke-auth 4.spring-eureke-order

spring-eureke-order там хранятся заказы(Entity Order)

Авторизация у меня простая через токены jwt

С токенами и авторизацией вроде все получилось

Но у меня вопросы возникли больше архитектурные:

  1. Как получать currentUser в сторонних сервисах например - spring-eureke-order

  2. И праавильная ли у меня архитектура разделение приложение?

  3. spring-eureke-zuul у меня проверяеть токены а запрос в базу делает spring-eureke-auth и UserDetai

Это spring-eureke-auth:

@Service   // It has to be annotated with @Service.
public class UserDetailsServiceImpl implements UserDetailsService  {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // hard coding the users. All passwords must be encoded.
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException
                    ("Username: " + username + " not found");
        } else {
            return user;
        }
    }

    // A (temporary) class represent the user saved in the database.
}

А это spring-eureke-zuul:

@EnableWebSecurity  // Enable security config. This annotation denotes config for spring security.
public class SecurityTokenConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtConfig jwtConfig;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
           http
        .csrf().disable()
            // make sure we use stateless session; session won't be used to store user's state.
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)     
        .and()
            // handle an authorized attempts 
            .exceptionHandling().authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED))  
        .and()
           // Add a filter to validate the tokens with every request
           .addFilterAfter(new JwtTokenAuthenticationFilter(jwtConfig), UsernamePasswordAuthenticationFilter.class)
        // authorization requests config
        .authorizeRequests()
                   .antMatchers(
                           HttpMethod.GET,
                           "/auth/api/whoami"
                   ).permitAll()
           // allow all who are accessing "auth" service
           .antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()  
           // must be an admin if trying to access admin area (authentication is also required here)
           .antMatchers("/gallery" + "/admin/**").hasRole("ADMIN")
           .antMatchers("/dic/**").permitAll()
           .antMatchers("/test/**").permitAll()

           // Any other request must be authenticated
           .anyRequest().authenticated(); 
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        // TokenAuthenticationFilter will ignore the below paths
        web.ignoring().antMatchers(
                HttpMethod.POST,
                "/auth/login",
                "/eureka/**"
        );
        web.ignoring().antMatchers(
                HttpMethod.GET,
                "/",
                "/page",
                "/eureka/**",
                "/graphiql",
                "/webjars/**",
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js"
        );
        // Allow eureka client to be accessed without authentication
        web.ignoring().antMatchers("/*/")//
                .antMatchers("/eureka/**")//
                .antMatchers(HttpMethod.OPTIONS, "/**"); // Request type options should be allowed.

    }

    @Bean
    public JwtConfig jwtConfig() {
           return new JwtConfig();
    }

Правильная ли архитектура что Principal попадает в zuul а дальше не проксируется.

Я понимаю что от начальной архитектуры проекта зависит практический все. Помогите пожалуйста с Архитектурой. Посоветуйте.

Может у кого то есть в git какие нибудь примеры или стартер. Или что почитать или где смотреть. Буду благодарен любой помощи.


Ответы (0 шт):