首页 > 其他分享 >Springboot基于注解鉴权

Springboot基于注解鉴权

时间:2024-09-11 14:50:26浏览次数:11  
标签:return String private public token user 注解 鉴权 Springboot

@Slf4j
@Component
public class ResourceInterceptor implements HandlerInterceptor {

    @Resource
    UserRoleService userRoleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        User user = UserUtil.getUser();
        if (user == null) {
            response.setStatus(401);
            return false;
        }
        Set<String> userRoles = new HashSet<>(userRoleService.userRole(user.getId()));
        if (handler instanceof HandlerMethod handlerMethod) {
            Method method = handlerMethod.getMethod();
            boolean annotationPresent = method.isAnnotationPresent(HasRole.class);
            if (annotationPresent) {
                HasRole annotation = method.getAnnotation(HasRole.class);
                String[] roleRequire = annotation.roles();
                for (String s : roleRequire) {
                    if (userRoles.contains(s)) {
                        return true;
                    }
                }
                response.setStatus(401);
                return false;
            }
        }

        return true;
    }
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface HasRole {
    String[] roles() default {};
}
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Resource
    private AuthenticationInterceptor authenticationInterceptor;

    @Resource
    private ResourceInterceptor resourceInterceptor;

    private static final String[] EXCLUDE_PATHS = {};

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor)
                .addPathPatterns("/api/**")
                .order(10);
        registry.addInterceptor(resourceInterceptor)
                .excludePathPatterns(EXCLUDE_PATHS)
                .addPathPatterns("/api/**")
                .order(100);
    }
}
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    JwtService jwtService;

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");
        if (token == null) {
            return true;
        }
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        String id;
        try {
            id = jwtService.extractClaim(token, c -> String.valueOf(c.get("id")));
        } catch (ExpiredJwtException e) {
            return true;
        }
        if (CheckUtil.isNumber(id)) {
            UserUtil.setUser(userService.getUserById(Long.parseLong(id)));
            return true;
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.remove();
    }
}
@Service
public class JwtService {
    @Value("${jwt.key}")
    private String secretKey;

    @Value("${jwt.expiration}")
    private long jwtExpiration;


    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    public String generateToken(User user) {
        return generateToken(new HashMap<>(), user);
    }

    public String generateToken(Map<String, Object> extraClaims, User user) {
        return buildToken(extraClaims, user, jwtExpiration);
    }

    public long getExpirationTime() {
        return jwtExpiration;
    }

    private String buildToken(
            Map<String, Object> extraClaims,
            User user,
            long expiration
    ) {
        return Jwts
                .builder()
                .setClaims(extraClaims)
                .setSubject(user.getUsername())
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(getSignInKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public boolean isTokenValid(String token, User user) {
        final String username = extractUsername(token);
        return (username.equals(user.getUsername())) && !isTokenExpired(token);
    }

    private boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    private Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    private Claims extractAllClaims(String token) {
        return Jwts
                .parserBuilder()
                .setSigningKey(getSignInKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    private Key getSignInKey() {
        byte[] keyBytes = Decoders.BASE64.decode(secretKey);
        return Keys.hmacShaKeyFor(keyBytes);
    }
}
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.5</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.5</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.5</version>
        </dependency>

 

 

jwt:
  key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  expiration: 86400000

 

使用

@HasRole(roles = {"admin"})

 

标签:return,String,private,public,token,user,注解,鉴权,Springboot
From: https://www.cnblogs.com/namedlxd/p/18408212

相关文章

  • Springboot 配置redis
    @ConfigurationpublicclassRedisConfig{@Value("${spring.data.redis.host}")privateStringredisHost;@Value("${spring.data.redis.port}")privateintredisPort;@Bean(name="jedisConnectionFactory")......
  • Springboot使用kaptcha生成验证码
    <dependency><groupId>com.youkol.support.kaptcha</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version></dependency>importcom.google.code......
  • Springboot 统一返回接口
    importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;@Data@AllArgsConstructor@NoArgsConstructorpublicclassCommonResponse<T>{privateTdata;privateStringmessage;privateintcode;public......
  • Springboot LocalDateTime 格式化
    importcom.fasterxml.jackson.databind.ser.std.ToStringSerializer;importcom.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;importcom.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;importcom.fasterxml.jackson.datatype......
  • Springboot枚举自定义序列化
    packagexxxxxxxxxxxxx;importcom.fasterxml.jackson.core.JsonGenerator;importcom.fasterxml.jackson.databind.JsonSerializer;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.SerializerProvider;importcom.fasterx......
  • 【JAVA开源】基于Vue和SpringBoot员工绩效考核系统
    本文项目编号T021,文末自助获取源码\color{red}{T021,文末自助获取源码}......
  • 【JAVA开源】基于Vue和SpringBoot大学生入学审核系统
    本文项目编号T022,文末自助获取源码\color{red}{T022,文末自助获取源码}......
  • 【JAVA开源】基于Vue和SpringBoot房屋租赁系统
    本文项目编号T020,文末自助获取源码\color{red}{T020,文末自助获取源码}......
  • 摄影分享|基于Springboot的摄影分享网站设计与实现(源码+数据库+文档)
    摄影分享源码|基于SpingBoot+vue的摄影分享网站|摄影分享网站源码影分享网站源码:摄影分享网站能够高效管理,使信息管理方法更为科学和规范化,摄影分享网站应用Java语言表达开展代码编写,摄影分享网站规范化管理信息具备安全性强、工作效率高、内存空间大、成本费用低等特点。它能......
  • 基于Springboot的养老院管理系统设计与实现毕业设计-附源码
    养老院|养老院管理系统源码|养老院管理系统设计与实现|基于Springboot的养老院管理系统养老院管理系统源码:计算机上安装养老院管理系统软件来发挥其高效地信息处理的作用,养老院管理系统的有效运用可以帮助管理人员准确快速地处理信息,养老院管理系统在对开发工具的选择上也很慎......