OAUTH2: при доступе к конечной точке REST из пользовательского интерфейса клиента для защиты URI возвращается anonymousUser - PullRequest
0 голосов
/ 02 мая 2018

Я работаю над пружинной безопасностью OAUTH2, я должен достичь http://localhost:8082/ui - конечная точка REST из пользовательского интерфейса клиента, которая приведет меня к защищенному URI http://localhost:8082/secure после входа на сервер аутентификации http://localhost:8081/auth/login.

Но вместо этого после нажатия на пользовательском интерфейсе клиента http://localhost:8082/ui он напрямую выводит меня на http://localhost:8082/secure,, не запрашивая страницу входа. и на защищенной странице возвращается значение «anonymousUser».

Я поделился своим клиентом и сервером ниже, и возвращаемое значение «Добро пожаловать, пользователь! == anonymousUser». Любая помощь будет очень признателен, если я делаю что-то не так.

моя клиентская конфигурация

@EnableOAuth2Sso
@Configuration
@EnableWebSecurity
public class OauthConfig extends WebSecurityConfigurerAdapter {

     @Autowired
        private OAuth2ClientContextFilter oauth2ClientContextFilter;



    @Override
    protected void configure(HttpSecurity http) throws Exception {

    http
        .authorizeRequests()
        .antMatchers("/**")    
       .permitAll()

       .antMatchers("/", "/login/**")     
       .permitAll()
            .anyRequest()
            .authenticated().and()
            .httpBasic().and().addFilterAfter(oauth2ClientContextFilter, SecurityContextPersistenceFilter.class);
        }

    @Bean
    protected OAuth2RestTemplate OAuth2RestTemplate(
        OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
      return new OAuth2RestTemplate(resource, context);
    }
    }

application.yml

server:
  port: 8082
  servlet:
    context-path: /ui
  session: 
    cookieName: UISESSION

 security:
   oauth2: 
    client: 
      clientId: ClientId
      clientSecret: secret
      accessTokenUri: http://localhost:8081/auth/oauth/token
      userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
      scope: openid
    resource: 
      userInfoUri: http://localhost:8081/auth/rest/hello/principal
      preferTokenInfo: false

application.properties

spring.thymeleaf.cache= false
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

server.port= 8082
server.servlet.session.cookie.name=UISESSION

spring.thymeleaf.mode=LEGACYHTML5


management.endpoints.web.expose=*

сервер авторизации на стороне сервера

@Configuration
@EnableAuthorizationServer
public class AuthorisationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;



    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // TODO Auto-generated method stub
        //security.allowFormAuthenticationForClients();
        security.tokenKeyAccess("permitAll()")
        .checkTokenAccess("isAuthenticated()");

    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory().withClient("ClientId")//.authorities("ROLE_ADMIN")
        .secret("{noop}secret")
        .authorizedGrantTypes("authorization_code").scopes("user_info").autoApprove(true);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // TODO Auto-generated method stub
        endpoints.authenticationManager(authenticationManager);
    }

}

сервер ресурсов на стороне обслуживания

@EnableResourceServer
@Configuration
@Order(1000)    
public class ResourceServerConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager; 
    @Autowired

    private  UserDetailsService customUserDetailsService;

    @Autowired
      public ResourceServerConfig(AuthenticationManager authenticationManager, 
              CustomUserDetailsService customUserDetailsService) {
        this.authenticationManager = authenticationManager;
        this.customUserDetailsService = customUserDetailsService;
      }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.requestMatchers().antMatchers("/login","/oauth/authorize").and().authorizeRequests()
        .anyRequest().authenticated().and().formLogin().permitAll();


    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {


        auth.parentAuthenticationManager(authenticationManager).
        userDetailsService(customUserDetailsService);

    }
}

Серверная служба

@Service
public class CustomUserDetailsService implements UserDetailsService{

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        Optional<Users> userOptional= userRepository.findByName(username);
        userOptional.orElseThrow(() -> new UsernameNotFoundException("user not found"));
        return userOptional.map(users -> new CustomUserDetails(users)).get();
    }


}
...