Spring Boot 实现通用 Auth 认证的 4 种方式!

本文详细介绍了在Spring Boot中实现通用Auth认证的四种方法:使用拦截器、参数解析器、Aspect切面以及Filter。通过创建自定义拦截器、参数解析器和Filter,实现了请求的拦截和验证,包括在Controller前处理请求参数和白名单校验。此外,文章还探讨了这些方法的适用场景和调用顺序,并提供了完整的代码示例。
摘要由CSDN通过智能技术生成
  1. 定义拦截器类 AppkeyInterceptor 类并实现 HandlerInterceptor 接口。

  2. 实现其 preHandle() 方法;

  3. 在 preHandle 方法内通过注解和参数判断是否需要拦截请求,拦截请求时接口返回 false

  4. 在自定义的 WebMvcConfigurerAdapter 类内注册此拦截器;

AppkeyInterceptor 类如下:

@Component

public class WhitelistInterceptor implements HandlerInterceptor {

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

Whitelist whitelist = ((HandlerMethod) handler).getMethodAnnotation(Whitelist.class);

// whitelist.values(); 通过 request 获取请求参数,通过 whitelist 变量获取注解参数

return true;

}

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

// 方法在Controller方法执行结束后执行

}

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

// 在view视图渲染完成后执行

}

}

扩展

要启用 拦截器还要显式配置它启用,这里我们使用 WebMvcConfigurerAdapter 对它进行配置。需要注意,继承它的的 MvcConfiguration 需要在 ComponentScan 路径下。

@Configuration

public class MvcConfiguration extends WebMvcConfigurerAdapter {

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addIntercepto

Spring Boot提供了Spring Security来实现OAuth2认证,下面是Spring Boot OAuth2认证过程的简要流程: 1. 用户访问客户端,客户端需要获取用户授权,重定向到授权服务器的授权页面; 2. 用户在授权页面输入账号密码并授权,授权服务器验证用户身份并返回授权码; 3. 客户端使用授权码向授权服务器请求访问令牌; 4. 授权服务器验证授权码并颁发访问令牌; 5. 客户端使用访问令牌向资源服务器请求数据。 下面是Spring Boot OAuth2认证的源码实现: 1. 导入OAuth2依赖 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.0.RELEASE</version> </dependency> ``` 2. 配置授权服务器 ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsService userDetailsService; @Autowired private DataSource dataSource; @Autowired private PasswordEncoder passwordEncoder; @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource) .withClient("client") .secret(passwordEncoder.encode("secret")) .authorizedGrantTypes("password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(1800) .refreshTokenValiditySeconds(3600); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore()) .authenticationManager(authenticationManager) .userDetailsService(userDetailsService); } } ``` 3. 配置资源服务器 ```java @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/**").authenticated() .and().csrf().disable(); } } ``` 4. 配置安全认证 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and().formLogin().permitAll(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 以上是Spring Boot OAuth2认证的简要流程和源码实现,具体的实现细节可以参考Spring官方文档和源码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值