OAuth2AuthenticationToken 是Spring Security OAuth2模块中的一个类,用于表示通过OAuth2协议认证后的用户身份信息。它包含了访问令牌(tokenValue)、客户端ID、授权类型等信息。
类型:
应用场景:
import org.springframework.security.oauth2.server.resource.authentication.OAuth2AuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TokenController {
@GetMapping("/token")
public String getTokenValue(OAuth2AuthenticationToken authentication) {
if (authentication != null) {
return authentication.getToken().getTokenValue();
}
return "No token found";
}
}
问题1:无法获取tokenValue
原因:
解决方法:
Authorization: Bearer <token>
。@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/token").authenticated()
)
.oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer
.jwt(jwt ->
jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())
)
);
}
private JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(new JwtGrantedAuthoritiesConverter());
return converter;
}
}
问题2:获取到的tokenValue无效
原因:
解决方法:
通过以上步骤,可以有效解决从OAuth2AuthenticationToken
获取tokenValue
时可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云