【问题标题】:How to use Spring OAuth2 JWT Token?如何使用 Spring OAuth2 JWT 令牌?
【发布时间】:2015-04-16 21:10:32
【问题描述】:

我们希望使用 Spring OAuth2 JWT 令牌支持。我们的架构如下:Spring 只提供一个 REST 接口,前端是用 AngularJS 构建的,它查询 Spring-REST 接口。出于授权目的,我们的前端团队想要使用 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 "";
}

但它似乎不起作用。

【问题讨论】:

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


    【解决方案1】:

    您可以查看新的spring-cloud-samplessso 示例。对我来说,这是了解它是如何完成的最好的示例。

    此外,一旦您开始了解它,您可以阅读this tutoiral,它更具技术性并且更多地了解如何使用 RSA 非对称密钥对。

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 2019-01-20
      • 2018-08-03
      • 2016-08-12
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2020-04-23
      相关资源
      最近更新 更多