Spring Security OAuth2简单配置

Sho*_*gun 7 java spring spring-mvc spring-security spring-security-oauth2

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

  • 我有一个"密码"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 =密码*,用户名密码(用户提供的).
  • 我在JSON响应中收到*ACCESS_TOKEN*(和其他一些东西).
  • 我使用*ACCESS_TOKEN*来查询URL(使用简单的GET请求),它将提供用户的信息.
  • 我在HttpSession中设置信息并将用户视为已登录.

它可以在2个HTTP请求中完成.我只是不想这样做,而是使用"更安全"的方式而不是Spring Security OAuth2.

你能想到我需要做什么"简单"配置才能完成这项工作吗?

Dav*_*yer 8

不要让火花样品混淆你(它比你似乎需要的更多).是对你很简单?

@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
    }

}

}
Run Code Online (Sandbox Code Playgroud)

那是auth服务器.客户端也很简单(例如Spring OAuth项目中的客户端).PS这是所有Spring OAuth 2.0的东西(尚未发布),但我们正在研究它(而且使用XML配置的1.0功能确实不那么重).

注意这种方式会破坏OAuth2的对象(webapp客户端应该收集用户凭据).你应该考虑使用grant_type=authorization_code.