之前做的大部分都是基于单体的springboot项目,对于权限这一块直接套用springsecurity就可以搞定了
但是现在随着微服务分布式架构的流行,越来越多的项目都拆解成一个个的微服务,因此需要重构权限这一块,这里我采用的是在网关gateway层进行认证授权,根据认证结果以及角色来判断是否放行该请求:
大致围绕下面三个需求:
- 基于用户-角色-权限控制
- 权限粒度控制到具体的请求URL
- 当用户的角色或者权限变动后,已获授权的用户需要重新登录授权
项目结构如图所示:
认证中心
springcloud-serve
登录认证授权等主要采用Spring security + redis+token机制,那么得首先配置WebSecurityConfig,这里看到的redis配置主要是为了满足需求点3(当用户的角色或者权限变动后,已获授权的用户需要重新登录授权)
登录控制:
对应业务层:
@Override
public ResponseResult login(LoginParam loginParam, HttpServletRequest request) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginParam.getName(),loginParam.getPassword());
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
if(Objects.isNull(authenticate)){
throw new RuntimeException("用户名或密码错误");
}
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
// 生成当前用户登录凭证
String token = UUID.randomUUID().toString().replaceAll("-", "");
logger.info("当前账号对应的token是: {}",token);
SysUser sysUser = loginUser.getUser();
Permission permission = new Permission();
// 获取当前登录用户所属的角色以及该角色可以访问哪些url,这里暂定写死,正常来讲是从数据库获取
String roleName = "admin";
List<String> urls = new ArrayList<>();
urls.add("/api/serve/list");
urls.add("/api/serve/test");
permission.setRoleName("admin");
permission.setUrls(urls);
// 封装
redisTemplate.opsForValue().set(token,permission,600, TimeUnit.SECONDS);
return new ResponseResult(200,"登录成功",token);
}
springsecurity配置
package com.cd.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.context.SecurityContextRepository;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启权限校验注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
/**
* 注入认证管理器
* @return
* @throws Exception
*/
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//关闭csrf
.csrf().disable()
//不通过Session获取SecurityContext
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// 对于登录接口 允许匿名访问
.antMatchers("/serve/login").permitAll();
// 匿名访问的意思是,未登录的状态可以访问该路径,但是如果是已经登陆的状态,就不能访问该接口
// 除上面外的所有请求全部需要鉴权认证
}
/**
* 自定义密码加密解密方式
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
网关微服务层过滤器:
gateway
package com.cd.filter;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.cd.pojo.Permission;
import com.cd.pojo.ResponseResult;
import com.cd.pojo.SysUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Service
public class AuthorizationFilter implements GlobalFilter, Ordered {
@Autowired
private RedisTemplate redisTemplate;
private static final Logger logger = LoggerFactory.getLogger(AuthorizationFilter.class);
AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
HttpHeaders headers = request.getHeaders();
//3. 如果是登录请求则放行
if (request.getURI().getPath().contains("/serve/login")) {
return chain.filter(exchange);
}
String token = request.getHeaders().getFirst("token");
if (StringUtils.isEmpty(token)){
// 构造错误响应体
ResponseResult errorResponse = new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"token无效");
errorResponse.setCode(HttpStatus.UNAUTHORIZED.value());
// 将错误响应体转换为JSON字符串
String json = null;
json = JSONUtil.toJsonStr(errorResponse);
// 设置响应消息体
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
DataBuffer buffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
return response.writeWith(Mono.just(buffer));
}
String path = request.getURI().getPath();
logger.info("request path:{}", path);
//3、判断请求的URL是否有权限
boolean b = hasPermission(token, path);
if (!b){
return getVoidMono(response, 403, "无访问权限");
}
return chain.filter(exchange);
}
private boolean hasPermission(String headerToken, String path){
if (StringUtils.isEmpty(headerToken)){
return false;
}
// 获取token里面的内容
Permission permission = (Permission) redisTemplate.opsForValue().get(headerToken);
if (Objects.isNull(permission)){
return false;
}
// 取出权限信息
List<String> urls = permission.getUrls();
boolean b = urls.stream().anyMatch(authority -> antPathMatcher.match(authority, path));
return b;
}
private Mono<Void> getVoidMono(ServerHttpResponse response, int i, String msg) {
// 构造错误响应体
ResponseResult errorResponse = new ResponseResult(HttpStatus.FORBIDDEN.value(),msg);
errorResponse.setCode(HttpStatus.FORBIDDEN.value());
// 将错误响应体转换为JSON字符串
String json = null;
json = JSONUtil.toJsonStr(errorResponse);
// 设置响应消息体
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
DataBuffer buffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
return response.writeWith(Mono.just(buffer));
}
@Override
public int getOrder() {
return 0;
}
}
至此完成授权认证:文章来源:https://www.toymoban.com/news/detail-686524.html
代码地址文章来源地址https://www.toymoban.com/news/detail-686524.html
到了这里,关于SpringCloudGateWay+nacos+redis+springsecurity实现多微服务统一授权认证的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!