Spring Security OAuth2 AuthorizationServer

时间:2015-03-19 15:22:41

标签: spring-security spring-security-oauth2 microservices

我正在玩spring-security-oauth2。我尝试使用身份验证后端构建一些微服务。

我设置了一个具有以下依赖关系的简单Spring启动项目

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.0.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

和一个配置类

@Configuration
public class SecurityConfiguration {

    @Autowired
    @Qualifier("clientDetailsServiceBean")
    private ClientDetailsService clientDetailsService;

    @Autowired
    @Qualifier("userDetailsServiceBean")
    private UserDetailsService userDetailsService;

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = true, prePostEnabled = true)
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        @Bean(name = "authenticationManagerBean")
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().permitAll().and().userDetailsService(userDetailsService).formLogin().and().httpBasic();
        }
    }

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

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

        @Bean
        public ApprovalStore approvalStore() throws Exception {
            TokenApprovalStore store = new TokenApprovalStore();
            store.setTokenStore(tokenStore());
            return store;
        }

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

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

        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security.checkTokenAccess("permitAll()");
            security.allowFormAuthenticationForClients();
        }

    }

我的Client-和UserDetailsS​​ervice的实现非常简单,总是返回一个对象

@Service("clientDetailsServiceBean")
public class ClientDetailsServiceBean implements ClientDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientDetailsServiceBean.class);

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        LOGGER.info("Load client {}", clientId); 
        BaseClientDetails details = new BaseClientDetails();
        details.setClientId(clientId);
        details.setAuthorizedGrantTypes(Arrays.asList("password", "refresh_token", "client_credentials"));
        details.setScope(Arrays.asList("trust"));
        details.setAutoApproveScopes(Arrays.asList("trust"));
        details.setAuthorities(Arrays.asList(new SimpleGrantedAuthority("client_role2")));
        details.setResourceIds(Arrays.asList("clients"));
        details.setClientSecret("secret");

        return details;
    }

}
@Service("userDetailsServiceBean")
public class UserDetailsServiceBean implements UserDetailsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsServiceBean.class);

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LOGGER.info("Load user {}", username);
        return new User(username, "password", Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")) );
    }
}

但是,当我尝试通过

接收accessToken时
curl http://localhost:8081/oauth/token -d grant_type=client_credentials -d client_id=web_client -d client_secret=secret

我收到错误“访问此资源需要完全身份验证”,当我尝试

curl http://localhost:8081/oauth/token -d grant_type=client_credentials -d client_id=web_client -d client_secret=secret --user web_client:secret

我收到错误“凭据错误”。从我的观点来看,两者都应该有效,但似乎缺少我的配置。

OAuth还有其他一些我不清楚的事情: 我尝试使用spring-security和自定义登录表单构建一个spring-mvc应用程序。弹簧安全性可以处理令牌请求和刷新周期而无需重定向到身份验证应用程序吗?

如果是事件驱动的应用程序,可以确保令牌有效吗?如果失败,用户点击按钮并写入一个事件,但是处理这个事件将在几个小时之后。如何使用用户凭据处理事件?

1 个答案:

答案 0 :(得分:1)

您的内部@Configuration类需要是静态的。我对应用程序启动感到惊讶,可能整个SecurityConfiguration实际上都没有被使用。

  

可以通过Spring安全性处理令牌请求和刷新周期而无需重定向到身份验证应用程序吗?

自然。您是否阅读过规范中的密码和refresh_token授权?但是在Web UI中,强烈建议您使用授权代码授权(使用重定向),以便用户只在受信任的位置输入其凭据。

  

用户点击按钮并写入一个事件,但是处理这个事件将在几个小时后完成。如何使用用户凭据处理事件?

刷新令牌可能是最好的方法。事件显然需要是安全的,因为它必须包含刷新令牌。