Spring Security OAuth2简单配置


问题内容

我有一个简单的项目,需要以下简单配置:

  • 我有一个“ password” grant_type,这意味着我可以提交用户名/密码(用户在我的登录表单中输入),并在成功时获取一个access_token。
  • 使用该access_token,我可以请求一个API并获取用户的信息。

我知道API的URI,我不需要任何大的东西(我在https://github.com/spring-projects/spring-security-
oauth/tree/master/samples
上看到了配置),而且看起来很大。

我可以这样想:

  • 执行一个简单的HTTP请求,并提供 client_id client_secret grant_type = password 用户名密码 (用户提供的 密码 )。
  • 我在JSON响应中收到 ACCESS_TOKEN (和其他一些东西)。
  • 我使用 ACCESS_TOKEN 查询URL(使用简单的GET请求),该URL将提供用户的信息。
  • 我在HttpSession中设置信息,并认为该用户已登录。

可以在2个HTTP请求中完成。我只是不想这样做,而是在Spring Security OAuth2中使用“更安全”的方法。

您能想到我需要做的“简单”配置吗?


问题答案:

不要让sparklr样本使您感到困惑(它所做的远远超出您的预期)。就是这个简单的够吗?

@ComponentScan
@EnableAutoConfiguration
public class Application {

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

@Configuration
@Order(Ordered.LOWEST_PRECEDENCE - 100)
protected static class OAuth2Config extends OAuth2AuthorizationServerConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // @formatter:off
        auth.apply(new InMemoryClientDetailsServiceConfigurer())
            .withClient("my-trusted-client")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write", "trust")
                .accessTokenValiditySeconds(60)
        .and()
            .withClient("my-client-with-secret")
                .authorizedGrantTypes("client_credentials")
                .authorities("ROLE_CLIENT")
                .scopes("read")
                .secret("secret");
    // @formatter:on
    }

}

}

那就是认证服务器。客户端也很容易(例如Spring OAuth项目中的客户端)。PS这是Spring
OAuth 2.0的全部内容(尚未发布),但是我们正在努力(而XML配置的1.0功能确实没有那么重)。

注意:这种方式击败了OAuth2的对象(Webapp客户端
应该收集用户凭据)。您应该考虑使用grant_type=authorization_code