【问题标题】:Use Spring Security with JDBC backend将 Spring Security 与 JDBC 后端一起使用
【发布时间】:2016-03-01 05:49:20
【问题描述】:

我已按照 Spring Security 教程的本章中的步骤进行操作:

Go to tutorial on spring.io

我已经构建了一个完美运行的应用程序:

然后我想实现一个 JDBC 后端,如本例中所述:

Go to example on GitHub

我更改了初始项目,如 GitHub 上的示例应用所示:

现在资源服务器似乎无法在/uaa/user 端点检查令牌:

执行的命令:

来自 OAuth2 授权服务器的日志

2016-02-28 12:35:08.762  INFO 1029 --- [nio-9999-exec-3] o.s.s.o.p.token.store.JdbcTokenStore     : Failed to find access token for token 41b1504d-b985-40e0-80a8-94c09992aafe
2016-02-28 12:37:58.604  INFO 1029 --- [nio-9999-exec-7] o.s.s.o.p.token.store.JdbcTokenStore     : Failed to find access token for token 41b1504d-b985-40e0-80a8-94c09992aafe
2016-02-28 12:44:06.845  INFO 1029 --- [nio-9999-exec-6] o.s.s.o.p.token.store.JdbcTokenStore     : Failed to find access token for token 41b1504d-b985-40e0-80a8-94c09992aafe

来自资源服务器的日志

2016-02-28 12:37:42.149  INFO 1186 --- [0.1-8181-exec-3] o.s.b.a.s.o.r.UserInfoTokenServices      : Getting user info from: http://localhost:9999/uaa/user
2016-02-28 12:37:42.228  INFO 1186 --- [0.1-8181-exec-3] o.s.b.a.s.o.r.UserInfoTokenServices      : Could not fetch user details: class org.springframework.security.oauth2.client.resource.UserRedirectRequiredException, A redirect is required to get the users approval
2016-02-28 12:37:58.600  INFO 1186 --- [0.1-8181-exec-5] o.s.b.a.s.o.r.UserInfoTokenServices      : Getting user info from: http://localhost:9999/uaa/user
2016-02-28 12:37:58.623  INFO 1186 --- [0.1-8181-exec-5] o.s.b.a.s.o.r.UserInfoTokenServices      : Could not fetch user details: class java.lang.IllegalArgumentException, URI is not absolute
2016-02-28 12:44:06.839  INFO 1186 --- [0.1-8181-exec-7] o.s.b.a.s.o.r.UserInfoTokenServices      : Getting user info from: http://localhost:9999/uaa/user
2016-02-28 12:44:06.848  INFO 1186 --- [0.1-8181-exec-7] o.s.b.a.s.o.r.UserInfoTokenServices      : Could not fetch user details: class org.springframework.security.oauth2.common.exceptions.InvalidRequestException, Possible CSRF detected - state parameter was present but no state could be found

以下是重要的类:

OAuth2 授权服务器:SaAuthApplication.class

@SpringBootApplication
@Configuration
@RestController
@EnableDiscoveryClient
@EnableResourceServer
@EnableAutoConfiguration
@EnableAuthorizationServer
public class SaAuthApplication {

    @Autowired
    private DataSource dataSource;

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

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

    @Configuration
    @EnableResourceServer
    protected static class ResourceServer extends ResourceServerConfigurerAdapter {

        @Autowired
        private TokenStore tokenStore;

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

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().authenticated();
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private AuthenticationManager auth;

        @Autowired
        private DataSource dataSource;

        private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

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

        @Bean
        protected AuthorizationCodeServices authorizationCodeServices() {
            return new JdbcAuthorizationCodeServices(dataSource);
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer security)
                throws Exception {
            security.passwordEncoder(passwordEncoder);
        }

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

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients.jdbc(dataSource)
                    .passwordEncoder(passwordEncoder)
                .withClient("my-trusted-client")
                    .authorizedGrantTypes("password", "authorization_code",
                            "refresh_token", "implicit")
                    .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                    .scopes("read", "write", "trust")
                    .resourceIds("oauth2-resource")
                    .accessTokenValiditySeconds(60).and()
                .withClient("my-client-with-registered-redirect")
                    .authorizedGrantTypes("authorization_code")
                    .authorities("ROLE_CLIENT").scopes("read", "trust")
                    .resourceIds("oauth2-resource")
                    .redirectUris("http://anywhere?key=value").and()
                .withClient("my-client-with-secret")
                    .authorizedGrantTypes("client_credentials", "password")
                    .authorities("ROLE_CLIENT").scopes("read")
                    .resourceIds("oauth2-resource").secret("secret");
            // @formatter:on
        }

    }

    @Autowired
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        // @formatter:off
            auth.jdbcAuthentication().dataSource(dataSource).withUser("dave")
                    .password("secret").roles("USER");
            // @formatter:on
    }

}

资源服务器:application.yml

security:
  oauth2:
    resource:
      user-info-uri: http://localhost:9999/uaa/user

资源服务器:SaEmployeeApplication.class

@SpringBootApplication
@EnableDiscoveryClient
@EnableResourceServer
public class SaEmployeeApplication {

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

}

OAuth2 授权服务器一切正常。我可以授权客户并取回令牌。但 资源服务器 似乎无法在 /uaa/user 端点检查令牌。

【问题讨论】:

  • 为什么你有两个@EnableResourceServer注解?尝试从SaEmployeeApplication 类中删除一个
  • @MangEngkus 它不起作用。如果我在删除 @EnableResourceServer 后尝试访问资源服务器,我会得到以下日志(当然是在获得新令牌之后):{"timestamp":1456737185144,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/api/employees/employees"}

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


【解决方案1】:

我会回答我自己的问题:

令牌的expires_in 值只有 59 秒。所以根本没有足够的时间来设置请求。

.accessTokenValiditySeconds(60) 设置 expires_in 值。

Read more

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 2011-01-15
    • 2011-04-16
    • 2011-01-23
    • 2014-12-20
    • 2014-12-11
    • 2015-01-25
    • 2012-10-30
    • 2011-11-30
    相关资源
    最近更新 更多