贝隆

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

https://cloud.tencent.com/developer/article/2040511

 

https://www.cnblogs.com/simpleito/p/15786122.html

https://blog.csdn.net/zlbdmm/article/details/118692985

 

https://blog.csdn.net/zlbdmm/article/details/118692985

https://www.cnblogs.com/fortuneju/p/17026770.html

https://zhuanlan.zhihu.com/p/538443308

https://cloud.tencent.com/developer/article/1972884

 

 

好的,以下是使用Spring Security实现Resource Server自定义Token校验逻辑的大致步骤:

  1. 创建一个自定义的过滤器,继承AbstractAuthenticationProcessingFilter。该过滤器表示我们要用来校验的Token。
java复制代码
public class MyTokenFilter extends AbstractAuthenticationProcessingFilter {

    public MyTokenFilter() {
        super("/**");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        String token = extractToken(request);

        if (token == null) {
            throw new BadCredentialsException("Missing Token.");
        }

        Authentication authRequest = new MyToken(token);
        return getAuthenticationManager().authenticate(authRequest);
    }

    private String extractToken(HttpServletRequest request) {
        // 根据实际情况,从请求中提取Token值
        return null;
    }
}
  1. 实现自定义校验逻辑。这个逻辑需要实现AuthenticationProvider接口,其中authenticate方法将会被Spring Security调用,以完成Token的校验流程。
java复制代码
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String token = ((MyToken) authentication).getToken();
        if (!jwtUtil.validateToken(token)) { // 自定义校验逻辑
            throw new BadCredentialsException("Invalid Token.");
        }
        return new MyToken(token); // 返回校验后的Token对象
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return MyToken.class.isAssignableFrom(aClass);
    }
}
  1. 配置Spring Security,以使用我们自定义的Token校验逻辑。可以在ResourceServerConfigurerAdapter中配置MyTokenFilter,并将MyAuthenticationProvider添加到AuthenticationManagerBuilder中。
java复制代码
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private MyAuthenticationProvider myAuthenticationProvider;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(new MyTokenFilter(), AbstractPreAuthenticatedProcessingFilter.class)
            .authorizeRequests()
            .anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationManager(authenticationManagerBean());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService());
        provider.setPasswordEncoder(passwordEncoder());
        return new ProviderManager(Collections.singletonList(myAuthenticationProvider));
    }
}
  1. 使用自定义Token进行校验。可以在Controller中使用Spring Security提供的@AuthenticationPrincipal注解,从而获取当前用户的Token对象,并进行相关操作。
java复制代码
@RestController
@RequestMapping("/api")
public class MyController {

    @GetMapping("/myApi")
    public ResponseEntity<String> myApi(@AuthenticationPrincipal MyToken token) {
        // 使用token进行相关逻辑操作
        return ResponseEntity.ok("Your Token is valid.");
    }
}

以上是一个简单的例子,使用Spring Security实现了Resource Server自定义的Token校验流程。当我们需要对Token进行自定义的校验操作时,可以按照这个方法在Resource Server中增加自定义的Token校验逻辑来完成。

 

 

如果你想要在Resource Server中自定义校验Token,可以按照以下步骤进行操作:

  1. 创建一个CustomAccessTokenConverter类,继承DefaultAccessTokenConverter。该类表示我们要用来自定义校验的Token。
java复制代码
@Component
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        // 自定义校验逻辑
        if (customValidate(map)) {
            return super.extractAuthentication(map);
        } else {
            throw new InvalidTokenException("Invalid Token.");
        }
    }

    // 实现自定义Token校验逻辑
    public boolean customValidate(Map<String, ?> map) {
        // 根据实际情况,实现自己的Token校验逻辑
        return true;
    }
}
  1. 配置Resource Server,以使用我们自定义的Token校验逻辑。在ResourceServerConfigurerAdapter类中,注入CustomAccessTokenConverter,并将其配置为Token的解析器。
java复制代码
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private CustomAccessTokenConverter customAccessTokenConverter;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenServices(tokenServices());
    }

    @Bean
    public ResourceServerTokenServices tokenServices() {
        RemoteTokenServices tokenServices = new RemoteTokenServices();
        tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        tokenServices.setClientId("client_id");
        tokenServices.setClientSecret("client_secret");
        tokenServices.setAccessTokenConverter(customAccessTokenConverter); // 设置自定义的Token解析器
        return tokenServices;
    }
}
  1. 在需要进行Token校验的API方法上,使用@AuthenticationPrincipal注解获取当前用户的Token对象,并进行相关操作。
java复制代码
@RestController
@RequestMapping("/api")
public class MyController {

    @GetMapping("/myApi")
    public ResponseEntity<String> myApi(@AuthenticationPrincipal OAuth2Authentication auth) {
        // 使用token进行相关逻辑操作
        return ResponseEntity.ok("Your Token is valid.");
    }
}


https://juejin.cn/post/6985893815500406791

如果你需要在 JWT Token 校验之后再增加自定义的校验,可以实现 ResourceServerConfigurerAdapter 接口,并重写 configure(HttpSecurity http) 方法和 configure(ResourceServerSecurityConfigurer resources) 方法。

以下是一个示例代码,仅供参考:

java复制代码
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

  // 自定义的 token 校验服务
  @Autowired
  private TokenValidationService tokenValidationService;

  @Override
  public void configure(HttpSecurity http) throws Exception {
    // 调用父类方法来配置 JWT Token 校验
    super.configure(http);

    // 在 JWT Token 校验之后,增加自定义校验拦截器
    http.authorizeRequests()
        .antMatchers("/api/**").authenticated()
        .anyRequest().access(new CustomAccessDecisionVoter());

    // 添加过滤器链
    http.addFilterAfter(new CustomFilter(), JwtAuthorizationTokenFilter.class);
  }

  @Override
  public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    // 配置资源服务器的安全性质,例如 token 的校验服务等
    resources.tokenServices(tokenValidationService);
  }
}

在上述代码中,我们首先调用了父类的 configure(HttpSecurity http) 方法,以实现 JWT Token 校验。然后在 JWT Token 校验之后,通过 http.authorizeRequests() 方法增加了自定义校验拦截器和访问控制规则。最后,通过 http.addFilterAfter() 方法添加了自定义的过滤器链,该过滤器会在 JWT Token 校验之后执行。

 


https://blog.csdn.net/u012833261/article/details/115709381
https://www.cnblogs.com/process-h/p/15705390.html

 

 
posted on 2023-03-22 22:48  贝隆  阅读(57)  评论(0)    收藏  举报