我正在开发一个 spring boot 应用程序。该应用程序具有内存中的安全身份验证和一些登录详细信息。我想从这个应用程序访问一个 oauth2 类型的 API 接口(以获取用户信息)。
当我尝试使用 RestTemplate 访问 api 时,出现以下错误。
class org.springframework.security.authentication.UsernamePasswordAuthenticationToken cannot be cast to class org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken and org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken are in unnamed module of loader 'app')
我在Controller类中调用接口的代码如下:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
System.out.println("Authenticated user name"+authentication.getName());
OAuth2AuthenticationToken oAuth2AuthenticationToken = (OAuth2AuthenticationToken)authentication;
OAuth2AuthorizedClient oAuth2AuthorizedClient = oAuth2AuthorizedClientService.loadAuthorizedClient(oAuth2AuthenticationToken.getAuthorizedClientRegistrationId(), oAuth2AuthenticationToken.getName());
String tokenValue = oAuth2AuthorizedClient.getAccessToken().getTokenValue();
System.out.println("jwtAccessToken"+tokenValue);
String url = "https://<url to interface>";
org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
headers.add("Authorization","Bearer "+tokenValue);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<List<Object>> responseEntity= restTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<Object>>(){});
List<Object> body = responseEntity.getBody();
for (Object obj :
body) {
System.out.println(obj);
}
我在application.yaml文件中做了oauth2的配置,如下图:
aapp.api:
base-url: https://<url to interface>
# Activate profile(s) HERE ['security' or 'tokenauth']
# or alternatively in a JVM argument ('-Dspring.profiles.active=security')
spring.profiles.active: security
---
# Use this profile to let spring-security automatically fetch and refresh tokens for you.
spring:
profiles: security
# Supply credentials for authentication HERE!
aapp.api.security:
username: some username
password: pass
# Configure oauth2 registration and provider for api portal HERE!
spring.security.oauth2.client:
registration:
someClientId:
authorization-grant-type: password
client-id: <clientId>
client-secret: <clientSecret>
provider:
coba:
token-uri: https://<url to auth2 server>
我是 spring security 和 oauth2 的新手。我该如何解决这个问题。
The spring security configuration I used is as follows:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/test", "/logout").permitAll()
.antMatchers("/webjars/**", "/resources/**", "/css/**", "/images/**", "/templates/**" ).permitAll()
.antMatchers("/","/**","/release/**","/decline/**").hasAnyRole("USER","ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/dashboard?sortField=startDate&sortDir=asc",true)
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSIONID")
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password(new BCryptPasswordEncoder().encode("pass")).roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}