照搬了https://blog.csdn.net/WiLL_XS/article/details/104894724这篇文章的代码,先谢谢这位老哥,在这些代码的基础上根据自己的需求简化了很多
pom.xml:
<!--zuul 网关组件-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<!--权限安全验证框架-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--token生成工具-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
以上是必须会用到的jar
项目结构:
代码(都是上面图片结构中的类的代码,直接复制,只要jar没错就不会出错):
package com.wdz.config;
import com.wdz.filter.AuthenticationTokenFilter;
import com.wdz.util.exception.EntryPointUnauthorizedHandler;
import com.wdz.util.exception.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration // 声明为配置类
@EnableWebSecurity // 启用 Spring Security web 安全的功能
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 注册 401 处理器
*/
@Autowired
private EntryPointUnauthorizedHandler unauthorizedHandler;
/**
* 注册 403 处理器
*/
@Autowired
private MyAccessDeniedHandler accessDeniedHandler;
/**
* 注册 token 转换拦截器为 bean
* 如果客户端传来了 token ,那么通过拦截器解析 token 赋予用户权限
*
* @return
* @throws Exception
*/
@Bean
public AuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
AuthenticationTokenFilter authenticationTokenFilter = new AuthenticationTokenFilter();
authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean());
return authenticationTokenFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/getToken").permitAll() // 所有人可以访问
.anyRequest().authenticated() // 必须携带token
.and()
// 配置被拦截时的处理
.exceptionHandling()
.authenticationEntryPoint(this.unauthorizedHandler) // 添加 token 无效或者没有携带 token 时的处理
.accessDeniedHandler(this.access