要在Oauth2授权服务器中进行访问,必须进行完全身份验证

时间:2018-12-16 06:57:03

标签: spring-boot spring-security oauth-2.0 spring-security-oauth2

我已经配置了授权服务器,并且有这样的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());
    }


}

及其应用程序。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 :(得分:0)

/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);
    }
}