SHIRO学习系列

怎么通过注解实现shiro不校验url

在使用shiro的权限认证的时候,有时候,有些链接不需要shiro认证的。比如登录接口。在代码中写死,如下图:每次,有新的不需要认证的,都需要添加,忘了手动添加就会出问题。能不能添加一个自定义注解,在不需要shiro认证的方法或者类上直接加自定义注解来处理?答案:可以。以下为解决步骤:①:添加自定义注解import java.lang.annotation.ElementType;imp

在使用shiro的权限认证的时候,有时候,有些链接不需要shiro认证的。比如登录接口。在代码中写死,如下图:

2ff69ff0cd830cdf69e3abb5e51baf1b.png

每次,有新的不需要认证的,都需要添加,忘了手动添加就会出问题。能不能添加一个自定义注解,在不需要shiro认证的方法或者类上直接加自定义注解来处理?

答案:可以。

以下为解决步骤:

①:添加自定义注解

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 ShiroIgnoreAuth {
}

②:在进行权限校验时,可以通过判断方法上是否有 @ShiroIgnoreAuth 注解来决定是否进行权限校验。

例如:

8696a2bca719dabc4ebc3dfb0a843ad2.png

完整的代码如下:

import xxx.LoginServiceImpl;
import xxx.ShiroIgnoreAuth;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * 执行

原创不易,完成人机校验,阅读全文

相关推荐