我正试图在服务器/客户端上使用JWT和OAuth2进行单点登录。
除了用户名(我计划只嵌入jwt)之外,我没有资源可以从客户端外部请求。
我的服务器正在工作并处理jwt令牌就好了(使用postman的oauth2令牌认证进行测试)。我不知道如何处理客户端。
我需要让我的客户端成为ResourceServer吗?或者我应该使用@ EnableOAuth2Sso教程?
对于我的客户,我有以下规格:
我认为这是可能的,正是Single Sign On应该是什么。
我的第一个想法是使用@ EnableOAuth2Sso,但这不能正常工作:
我发现以下错误消息:可能检测到CSRF - 状态参数是必需的,但找不到状态
我猜有一个错误配置保存/使用/转换“state”参数。不过我想用它。
我找到了this comment并为客户端添加了不同的上下文路径。这将错误消息更改为:
org.springframework.security.authentication.BadCredentialsException:无法获取访问令牌由以下原因引起:org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException:请求访问令牌时出错。引起:org.springframework.web.client.HttpClientErrorException:401 null
码:
客户端应用:
@SpringBootApplication
@EnableOAuth2Sso
public class TestClientApplication
{
public static void main(String[] args) {
SpringApplication.run(TestClientApplication.class, args);
}
}
application.yml:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:8080/oauth/token
userAuthorizationUri: http://localhost:8080/oauth/authorize
authenticationScheme: query
clientAuthenticationScheme: form
resource:
jwt:
keyValue:
-----BEGIN PUBLIC KEY-----
...
这是我的服务器实现:
OAuth2Config:
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter
{
@Value("${resource.id:spring-boot-application}")
private String resourceId;
@Value("${access_token.validity_period:3600}")
int accessTokenValiditySeconds = 3600;
//todo
private static final String JWTSecretKey = "mySecretKey";
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public TokenEnhancer tokenEnhancer()
{
return new JwtTokenEnhancer();
}
@Bean
protected JwtAccessTokenConverter accessTokenConverter()
{
//todo use secure cert
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), JWTSecretKey.toCharArray());
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
return converter;
}
@Bean
public TokenStore tokenStore()
{
return new JwtTokenStore(accessTokenConverter());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
{
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(tokenEnhancer(), accessTokenConverter()));
endpoints
.tokenStore(tokenStore())
.tokenEnhancer(tokenEnhancerChain)
.authenticationManager(this.authenticationManager); //only needed for password grant, which we should only use in case of native/client side apps
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
{
//todo add redirect urls
clients.inMemory()
.withClient("trusted-app") //todo for postman testing only, remove in production!
.secret("secret")
.authorizedGrantTypes("client_credentials")
.authorities("ROLE_TRUSTED_CLIENT")
.scopes("read", "write")
.resourceIds(resourceId, "myprintforce")
.autoApprove(true)
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.and()
.withClient("client")
.secret("secret")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write")
.resourceIds("client", resourceId)
.autoApprove(true)
.accessTokenValiditySeconds(accessTokenValiditySeconds);
;
}
}
TokenEnhancer
public class JwtTokenEnhancer implements TokenEnhancer
{
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication)
{
Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("user", authentication.getName());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
WebSecurityConfig
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication().withUser("u").password("p").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
}
应用
@SpringBootApplication
public class OAuthServerApplication extends WebMvcConfigurerAdapter
{
public static void main(String[] args)
{
SpringApplication.run(OAuthServerApplication.class, args);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
问题是2台服务器使用相同的(localhost)机器。当他们有不同的contextPaths时,问题几乎就解决了。
通过更改配置文件中的一些条目,我得到了它的工作。
我删除了:authenticationScheme: query
和clientAuthenticationScheme: form
并添加了scope=read
它现在看起来像这样:
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:12000/authentication/oauth/token
userAuthorizationUri: http://localhost:12000/authentication/oauth/authorize
scope: read
resource:
jwt:
keyValue:
-----BEGIN PUBLIC KEY-----