check_token出现invalid_token

来源:4-6 搭建OAuth2资源服务器

卟想回憶

2020-04-28

授权服务器配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authenticationManager;
private final UserDetailsService userService;
public AuthorizationServerConfig(PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager, UserDetailsServiceImpl userService) {
    this.passwordEncoder = passwordEncoder;
    this.authenticationManager = authenticationManager;
    this.userService = userService;
}


@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            // 配置client_id
            .withClient("admin")
            // 配置client_secret
            .secret(passwordEncoder.encode("admin"))
            // 配置访问token的有效期
            .accessTokenValiditySeconds(3600)
            // 配置刷新token的有效期
            .refreshTokenValiditySeconds(864000)
            // 该客户端允许访问的微服务
            .resourceIds("platform-upms")
            // 配置redirect_uri,用于授权成功后的跳转
            .redirectUris("http://www.baidu.com")
            // 配置申请的权限范围
            .scopes("all")
            // 配置grant_type,表示授权类型
            .authorizedGrantTypes("authorization_code", "password", "refresh_token");
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager)
            .userDetailsService(userService);
}


@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.checkTokenAccess("isAuthenticated()");
}

}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/oauth/**", "/login/**", "logout/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .permitAll();
}

}
资源服务器配置
@Configuration
@EnableResourceServer
public class PlatformUpmsResourceServerConfig extends ResourceServerConfigurerAdapter {

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    //配置资源服务器的id,“现在我就是资源服务器order-server!!!”
    resources.resourceId("platform-upms");
}


@Override
public void configure(HttpSecurity http) throws Exception {
    http
            //.formLogin()
            // 当请求需要认证的时候跳转的url
            //.loginPage("/authentication/require")
            // 登录处理方式(前台发送请求的格式)
            //.loginProcessingUrl("/login")
            //.and()
            //放行的url
            .requestMatchers()
            .antMatchers("/sys/user/info/**","/test/**","/dict/**","/druid/**","/swagger-ui.html", "/v2/api-docs")
            .anyRequest()
            .and()
            //认证的url
            .authorizeRequests()
            .antMatchers("/sys/user/info/**","/test/**","/dict/**","/druid/**","/swagger-ui.html", "/v2/api-docs")
            .permitAll()
            //任何请求
            .anyRequest()
            //需要身份认证
            .authenticated()
            .and()
            //关闭跨站请求防护
            .csrf().disable()
            .cors().disable()
            //前后端分离采用JWT 不需要session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

}

@Configuration
@EnableWebSecurity
public class PlatformUpmsWebSecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
public ResourceServerTokenServices tokenServices(){
    RemoteTokenServices tokenServices = new RemoteTokenServices();
    tokenServices.setClientId("admin");
    tokenServices.setClientSecret("admin");
    tokenServices.setCheckTokenEndpointUrl("http://127.0.0.1:8001/oauth/check_token");
    return tokenServices;
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    OAuth2AuthenticationManager auth2AuthenticationManager = new OAuth2AuthenticationManager();
    auth2AuthenticationManager.setTokenServices(tokenServices());
    return auth2AuthenticationManager;
}

}
自定义实现的UserDetailsService
@Slf4j
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final RemoteUserService remoteUserService;

/**
 * 根据用户名登录
 * @param username 用户名
 * @return UserDetails
 * @throws UsernameNotFoundException UsernameNotFoundException
 */
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    CommonResult<UserInfo> result = remoteUserService.info(username);
    UserDetails userDetails = getUserDetails(result);
    return userDetails;
}
/**
 * 构建UserDetails
 *
 * @param result 用户信息
 * @return UserDetails
 */
private UserDetails getUserDetails(CommonResult<UserInfo> result) {
    return new PlatformUser(result.getData().getSysUser().getUsername(),
            result.getData().getSysUser().getPassword(),
            result.getData().getSysUser().getUserSignid(),
            result.getData().getSysUser().getDepId(),
            result.getData().getSysUser().getTenantId(),
            true,true,true,true,
            AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}

}

经过gateway网关可以正常获取token,但是带着token请求资源服务器时会出现
{
“error”: “invalid_token”,
“error_description”: “bearer 17dbaf3f-5962-4d92-ac9d-3edaa483be12”
}

写回答

1回答

卟想回憶

提问者

2020-04-28

我debug看提示获取不到我的token在内存里面,验token第一个函数返回的都是null

0
0

Spring Cloud微服务安全实战 可落地的安全方案

从API到复杂微服务场景,实战部署可落地的安全方案。

1029 学习 · 370 问题

查看课程