Для доступа к серверу авторизации Oauth2 требуется полная аутентификация - PullRequest
0 голосов
/ 16 декабря 2018

Я настроил сервер авторизации, и есть хранилище токенов jdbc следующим образом:

@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource oauthDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JdbcClientDetailsService clientDetailsService() {
        return new JdbcClientDetailsService(oauthDataSource());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(oauthDataSource());
    }

    @Bean
    public ApprovalStore approvalStore() {
        return new JdbcApprovalStore(oauthDataSource());
    }

    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(oauthDataSource());
    }

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

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {

    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .approvalStore(approvalStore())
                .authorizationCodeServices(authorizationCodeServices())
                .tokenStore(tokenStore());
    }

}

, а защита пружины выглядит следующим образом:

@EnableWebSecurity
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return new JdbcUserDetails();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/webjars/**","/resources/**");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //.authorizeRequests()
                //.antMatchers("/login**","/logout**").permitAll()
                //.antMatchers("/**").authenticated()
                //.and()
                .formLogin()
                .loginPage("/login")
                //.loginProcessingUrl("/login")
                //.usernameParameter("username")
                //.passwordParameter("password")

                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .and()
                .userDetailsService(userDetailsServiceBean());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceBean())
                .passwordEncoder(passwordEncoder());
    }


}

, а его application.yml -:

server.contextPath: /auth
spring:
    datasource:
        url: jdbc:oracle:thin:@192.168.192.129:1521:hamed
        hikari:
            connection-test-query: SELECT 1 FROM DUAL
            minimum-idle: 1
            maximum-pool-size: 5
        driver-class-name: oracle.jdbc.OracleDriver
        username: test
        password: test
        initialization-mode: always
    jpa:
      hibernate:
        ddl-auto: none
      database-platform: org.hibernate.dialect.Oracle12cDialect
      show-sql: true

logging:
 level:
   org.springframework.security: DEBUG
   org.hibernate.SQL: DEBUG
   org.hibernate.type.descriptor.sql.BasicBinder: TRACE

server:
 port: 8081
#keystore:
#  password: mySecretKey

Он успешно запущен.И клиент:

@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {

    @RequestMapping("/user")
    public Principal user(Principal principal) {
        return principal;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll()
                .anyRequest().authenticated()
                .and().logout().logoutSuccessUrl("/").permitAll()
                .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

    public static void main(String[] args) {
        SpringApplication.run(SocialApplication.class, args);
    }
}

, а application.yml клиента:

server:
  port: 8090

security:
  oauth2:
    client:
      clientId: curl_client
      clientSecret: reza
      accessTokenUri: http://localhost:8081/auth/oauth/token
      userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: http://localhost:8081/auth/user

logging:
  level:
    org.springframework.security: DEBUG

Необходимо отметить, что данные oauth_client_details:

    INSERT INTO oauth_client_details(client_id, 
resource_ids, 
client_secret, 
scope, 
authorized_grant_types, 
web_server_redirect_uri, 
authorities, 
access_token_validity, 
refresh_token_validity, 
additional_information, 
autoapprove
) VALUES('curl_client',
         'product_api', 
         'reza', 
         'read,write', 
         'client_credentials', 
         'http://127.0.0.1', 
         'ROLE_PRODUCT_ADMIN', 
         7200, 
         0, 
         NULL, 
        'true');

Но когда я запрашиваю http://localhost:8090/user, возникает следующее исключение:

Для доступа к этому ресурсу необходима полная аутентификация

В чем дело?

1 Ответ

0 голосов
/ 17 декабря 2018

/login** разрешить все должно быть выше /** authorizeRequests.Давайте попробуем это:

@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {

    @RequestMapping("/user")
    public Principal user(Principal principal) {
        return principal;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/", "/login**", "/webjars/**").permitAll()
            .antMatchers("/**").authenticated()
            .and().logout().logoutSuccessUrl("/").permitAll().and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

    public static void main(String[] args) {
        SpringApplication.run(SocialApplication.class, args);
    }
}
...