1

У меня есть приложение, в которое можно войти с или с помощью oauth2 alos. Но я встретил некоторые проблемы.Весенняя безопасность oauth2.0 restful и Form login config

То, что я встретил:

  • Когда я посещаю http://127.0.0.1/, он truns в/Логин страницу правильно.
  • Когда я нахожусь http://127.0.0.1/api/hellos, он также загружает страницу входа/входа, что именно неправильно. Я хочу, чтобы я мог получить доступ/api/hellos, используя oauth2.

Вот моя конфигурация безопасности:

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true) 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private SpringDataMyBatisUserDetailsService userDetailsService; 

    @Override 
    @Autowired 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
     .userDetailsService(this.userDetailsService) 
     .passwordEncoder(Manager.PASSWORD_ENCODER); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class); 
    } 

    @Configuration 
    @EnableAuthorizationServer 
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { 

     private final AuthenticationManager authenticationManager; 
     @Autowired 
     private TokenStore tokenStore; 
     @Autowired 
     private SpringDataMyBatisClientDetailsService clientDetailsService; 

     @Autowired 
     public AuthorizationServerConfig(AuthenticationManager authenticationManager) { 
      this.authenticationManager = authenticationManager; 
     } 

     /** 
     * Defines the security constraints on the token endpoints /oauth/token_key and /oauth/check_token 
     * Client credentials are required to access the endpoints 
     * 
     * @param oauthServer 
     * @throws Exception 
     */ 
     @Override 
     public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { 
      oauthServer 
      .tokenKeyAccess("permitAll()") 
      .checkTokenAccess("isAuthenticated()"); 
     } 

     /** 
     * Defines the authorization and token endpoints and the token services 
     * 
     * @param endpoints 
     * @throws Exception 
     */ 
     @Override 
     public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 
      endpoints 
      .authenticationManager(this.authenticationManager) 
      .tokenEnhancer(tokenEnhancer()) 
      .tokenStore(tokenStore); 
     } 

     @Override 
     public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 
      clients 
      .withClientDetails(clientDetailsService); 
     } 

     @Bean 
     public TokenEnhancer tokenEnhancer() { 
      return new CustomTokenEnhancer(); 
     } 

    } 

    @Order(1) 
    @Configuration 
    public class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
      .csrf().disable() 
      .authorizeRequests() 
      .antMatchers("/index.html", "/index.css", "/common.js", "/index.js", "/api/**").permitAll() 
      .anyRequest().authenticated() 
      .and() 
      .formLogin() 
      .and() 
      .logout() 
      .logoutSuccessUrl("/") 
      .and().exceptionHandling().accessDeniedPage("/error/403"); 
     } 

    } 

    @Configuration 
    @EnableResourceServer 
    @Order(2) 
    public class AuthorizationResourceConfig extends ResourceServerConfigurerAdapter { 

     @Autowired 
     private RestAuthenticationEntryPoint restAuthenticationEntryPoint; 
     @Autowired 
     private AuthenticationSuccessHandler successHandler; 
     @Autowired 
     private AuthenticationFailureHandler failureHandler; 
     @Autowired 
     private TokenStore tokenStore; 

     @Override 
     public void configure(ResourceServerSecurityConfigurer resources) throws Exception { 
      resources 
      .stateless(true) 
      .tokenStore(tokenStore); 
     } 

     @Override 
     public void configure(HttpSecurity http) throws Exception { 
      http 
      .authorizeRequests() 
      .and() 
      .anonymous().disable() 
      .sessionManagement() 
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
      .and().httpBasic() 
      .and() 
      .exceptionHandling() 
      .accessDeniedHandler(new OAuth2AccessDeniedHandler()) 
      .authenticationEntryPoint(restAuthenticationEntryPoint) 
      .and() 
      .authorizeRequests() 
      .antMatchers("/api/**").fullyAuthenticated(); 

     } 
    } 

} 

Я попробовал несколько способов, где я искал от google.But никто не может мне помочь. Итак, я действительно хочу, чтобы кто-то мог мне помочь, я буду признателен за вас.

Кроме того, самая полезная информация, которую я искал, - this.

ответ

0

u использовать этот «.antMatchers («/api/** »). FullAuthenticated();», в этом случае потребуется «LOG IN» для всех действий/api/.... ,, if u dont Хотите «войти» в форму для «127.0.0.1/api/hellos» u необходимо использовать только/api/без звезд

+0

Я не использую RESOURCE_PATH_MATCH. Я удалил его. – WhiteWater

+0

u использовать этот «.antMatchers («/api/** »). FullAuthenticated();», в этом случае потребуется «LOG IN» для всех действий/api/.... ,, if u dont Want «войти в систему» ​​для «http://127.0.0.1/api/hellos» u должен использовать только/api/без звезд – kuciB

+0

Вы можете неправильно понять. Мой проект состоит из двух разных частей: панели администрирования JSF и службы RESTfull. Я пытаюсь настроить весеннюю безопасность для использования разных методов проверки подлинности в зависимости от URL-адреса, который пользователь просматривает. – WhiteWater