我在我的项目中使用Spring Rest + OAUTH2 + React。为了创建授权服务器,我从示例中获得了一些代码。但问题是我无法理解代码。有人可以解释一下这段代码:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyPair keyPair = new KeyStoreKeyFactory(
new ClassPathResource("keystore.jks"), "suleman123".toCharArray())
.getKeyPair("resourcekey");
converter.setKeyPair(keyPair);
return converter;
}
/**
* This method configure client details service by using inMemory implementation. JDBC Implementation can also used
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("acme") // client id
.secret("acmesecret") // required for trusted clients
.authorizedGrantTypes("authorization_code", "refresh_token",
"password") // Grant types that are authorized for the client to use
.scopes("openid") // scope to which the client is limited
.autoApprove(true);
}
/**
* This method configure the grant types. By default all grant types are supported except password
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints.authenticationManager(authenticationManager).accessTokenConverter(
jwtAccessTokenConverter());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess(
"isAuthenticated()");
}
}
答案 0 :(得分:1)
Spring启动与自动配置一起使用。你在这里看到的是一个扩展spring自动配置类的人,以便根据他的需要进行自定义。
<强> TL; DR:强>
他们设置了一个基于JWT的oauth2授权服务器。
详细答案:
在这种情况下,通过组合@EnableAuthorizationServer
和扩展AuthorizationServerConfigurerAdapter
,您可以启用,操作和修改授权服务器。
JwtAccessTokenConverter
。 More on JWT。configure(ClientDetailsServiceConfigurer clients)
- 它们配置一个内存客户端以在应用程序中使用。configure(AuthorizationServerEndpointsConfigurer endpoints)
- 他们将默认authenticationManager
配置为spring初始化并注入配置类顶部并将accessTokenConverter
设置为使用jwtAccessTokenConverter
#1。这样做可以让他们在为新令牌排队时生成JWT令牌。configure(AuthorizationServerSecurityConfigurer oauthServer)
- 当有经过身份验证的用户(oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
)时,他们将所有端点设置为允许访问所有内容。