如何使用Spring OAuth2 JWT Token?

时间:2015-02-16 11:09:22

标签: spring rest spring-mvc oauth-2.0 jwt

我们希望使用Spring OAuth2 JWT Token支持。我们的架构如下:Spring只提供一个REST接口,前端是用AngularJS构建的,它查询Spring-REST-Interface。出于授权目的,我们的前端团队想要使用JWT。所以我看一下Spring的OAuth2 JWT支持,但仍然不知道如何与前端JWT-Tokens交谈。在阅读了一些小教程后,我实现了这个:

@Autowired
@Qualifier("defaultAuthorizationServerTokenServices")
private DefaultTokenServices tokenServices;

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

@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    //@Autowired
    private AuthenticationManager authManager;

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        return new JwtAccessTokenConverter();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')")
                   .checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')"); 
    }

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
        .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-registered-redirect")
            .authorizedGrantTypes("authorization_code")
            .authorities("ROLE_CLIENT")
            .scopes("read", "trust")
            .redirectUris("http://anywhere?key=value")
        .and()
        .withClient("my-client-with-secret")
            .authorizedGrantTypes("client_credentials", "password")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("read", "write")
            .secret("secret");
    }
}

我不确定工作流程是怎样的。我猜:前端访问/ oauth / authorization端点以授权其令牌,然后如果资源被授权访问资源,则每次请求资源时,Spring后端都必须检查JWT-Token?对?那么如何在请求REST端点时告诉Spring检查令牌?我用

试了一下
@RequestMapping("/projects")
@PreAuthorize("oauthClientHasRole('ROLE_CLIENT')")
public String getProjects() {
    return "";
}

但似乎没有用。

1 个答案:

答案 0 :(得分:0)

您可以查看新的spring-cloud-samples sso示例。对我而言,这是最好的样本,以了解它是如何完成的。

此外,一旦你了解它,你可以阅读this tutoiral,它更具技术性和技术性。更多关于如何使用RSA不对称密钥对进行操作。