Attribute注解(用于判断权限)

本文介绍了Attribute注解的基本原理、使用步骤及示例,并展示了如何利用Attribute进行权限验证。

一  Attribute原理:

Attribute注解,是附加上方法、属性、类等上面的标签,
可以通过方法的GetCustomAttribute获得粘贴的这个Attribute对象
通过反射调用到粘贴到属性、方法、类等等的对象
任务:改造ORM
ORM约定:类得名字与表的名字一样,主键必须是Id,
改造一下ORM(类名还可以和表名不一样,Id可以与主键不一样)

//在sayHello方法的描述信息MethodInfo上粘了一个RupengAttribute对象
//注解的值必须是常量,不能是动态算出来的 [RupengAttribute(Name=DateTime.Now.ToString())]
//[RupengAttribute(Name="rupengwnag")]
//一般特性Attribute的类名都以Attribute结尾,这样用的时候就不用谢"Attribute"了

二  Attribute步骤:

1 Attribute本身类
2 标记了Attribute的类
3 通过找到这个类的Attribute标记,从而先去执行上面的Attribute类

三 Attribute示例:

   //testAttribute.csProj

namespace testAttribute
{
    class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(Person);
            //1 获得SayHello()上的Attribute注解对象
            object[] objs = type.GetMethod("SayHello").GetCustomAttributes(typeof(AlibabaAttribute), true);
            foreach(object obj in objs)
            {
                AlibabaAttribute ali = obj as AlibabaAttribute;
                Console.WriteLine(ali.Name);
            }

            //2 在类中的方法中找到Obsolete注解对象
            MethodInfo[] methods = type.GetMethods();
            foreach(MethodInfo method in methods)
            {
                Object[] obsols = method.GetCustomAttributes(typeof(ObsoleteAttribute),true);
                if (obsols.Length>0)
                {
                    ObsoleteAttribute obsol = obsols[0] as ObsoleteAttribute;
                    Console.WriteLine("不能执行该方法:" + obsol.Message);
                }
            }

            //3 获得Love()的Attribute注解对象
            object[] objtens = type.GetMethod("Love").GetCustomAttributes(typeof(TengxunAttribute), true);
            foreach (object obj in objtens)
            {
                TengxunAttribute ten = obj as TengxunAttribute;
                Console.WriteLine(ten.Name);
            }

            Console.ReadKey();
        }
    }

    class Person
    {
        [Alibaba(Name="阿里人是幸福的")]
        public void SayHello()
        { 
        }

        [Obsolete("这个方法已过时,禁止访问")]
        public void F1()
        { 
        }

        [Tengxun(Name = "腾讯是我的最爱")]
        public void Love()
        { 
        }
    }

    //1
    [AttributeUsage(AttributeTargets.Method)]
    class AlibabaAttribute : Attribute
    {
        public AlibabaAttribute() { }
        public AlibabaAttribute(string name)
        {
            this.Name = name;
        }
        public string Name { get; set; }
    }

    //2
    class TengxunAttribute : Attribute
    {
        public string Name { get; set; }
    }
}

四  Attribute应用:

   当执行某个action方法时,先获得Attribute对象,用于检查权限

  //PermissionActionAttribute.cs

    /// <summary>
    /// 权限动作的 Attribute注解
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class PermissionActionAttribute:Attribute
    {
        public string Name { get; set; }
        public PermissionActionAttribute(string name)
        {
            this.Name = name;
        }
    }

  //BaseController.cs

public class BaseController : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            //需要约定方法:public void list(HttpContext context) //方法名和action一致
            #region 检查用户是否登录
            LoginHelper.CheckHasLogin(context);
            #endregion
            string action = context.Request["action"];
            if(action==null)
            {
                throw new Exception("未找到action:"+action);
            }
            Type type = this.GetType(); //this是被new的对象,即子类CategoryController等
            //try
            //{
                MethodInfo method = type.GetMethod(action);
                #region /获得该action的 Attribute注解对象
                //获得action该方法的 Attribute注解对象(注解对象的Name属性就是权限的名称,用于判断权限)
                object[] objAttrs = method.GetCustomAttributes(typeof(PermissionActionAttribute), true);
                if (objAttrs.Length > 0)
                {
                    PermissionActionAttribute paa = objAttrs[0] as PermissionActionAttribute;
                    AdminHelper.CheckHasPower(context, paa.Name);
                } 
                #endregion
                method.Invoke(this, new object[] { context }); //调用this对象的method方法 (参数列表是object[],其中一个参数是context)
            //}
            //catch(Exception ex) //如果找不到这个action方法,就说明这个action是错误的/不存在的
            //{
            //    throw new Exception("未知的action:"+action);
            //}
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }

  //CourseController.cs

            [PermissionAction("新增课程")]
           public void addnew(HttpContext context)
            {
                #region 新增展示
                string categoryidStr = context.Request["categoryid"];
                int categoryid = VolidHelper.CheckStrToInt(categoryidStr);
                TD_COURSE course = new TD_COURSE();
                course.VIDEOCATEGORYID = categoryid;
                RazorHelper.RazorParse(context, "~/Course/CourseAlter.cshtml", new { action = "addnew", course = course }); 
                #endregion
            }

 

posted on 2015-11-05 08:28 AdolphYang 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/adolphyang/p/4938226.html

<think>好的,我现在需要帮助用户解决在使用@PreAuthorize注解的Controller方法中,通过特殊token跳过权限验证的问题。首先,我得理解用户的具体需求。用户可能希望在某些情况下,比如使用特定的令牌(比如内部服务调用或测试时),绕过Spring Security的权限检查。这可能涉及到自定义权限判断逻辑,或者修改现有的安全配置。 首先,我需要回顾一下Spring Security的工作原理,特别是@PreAuthorize注解的处理机制。@PreAuthorize是基于方法级别的安全注解,它依赖于Spring AOP和Global Method Security配置。当方法被调用时,Spring Security会拦截调用并根据表达式的结果决定是否允许执行。用户想要的是在某些情况下,比如携带特定token时,跳过这个检查。 接下来,我需要考虑如何实现这一点。可能的思路包括: 1. **自定义权限表达式**:创建一个自定义的Spring Security表达式,在表达式中检查请求中的特殊token。例如,在@PreAuthorize中使用类似@customCheck的表达式,该表达式会验证token是否存在且有效。如果存在,则返回true,允许访问,否则进行正常的权限检查。 2. **使用BeanPostProcessor修改注解属性**:通过后处理Bean,动态修改Controller方法上的@PreAuthorize注解,比如在检测到特定条件时,将表达式改为始终允许的表达式(如"permitAll")。不过,这种方法可能比较复杂,涉及到AOP的底层处理,而且可能影响其他安全配置,需要谨慎处理。 3. **自定义AccessDecisionManager**:覆盖默认的访问决策管理器,在决策逻辑中加入对特殊token的判断。如果请求中包含有效token,则直接授予访问权限,否则继续原有的投票机制。这种方法需要对Spring Security的决策流程有较深的理解。 4. **结合过滤器或拦截器**:在请求到达Controller之前,通过自定义的过滤器检查特殊token,如果有效,则将当前用户的权限提升为具有所需权限的角色,或者设置SecurityContextHolder中的Authentication为已认证且有权限的状态。这样,后续的@PreAuthorize检查就会自然通过。 现在需要评估这些方法的可行性。用户提到可能使用BeanPostProcessor,这可能涉及到动态修改Bean的定义,但具体如何操作需要查阅相关文档。另外,用户还提到自定义注解,可能希望结合自定义注解和现有的安全机制。 例如,用户可以创建一个自定义注解如@SkipAuthWithToken,然后通过AOP或者拦截器在方法执行前检查请求中的token,如果符合条件,就绕过权限检查。这种方法需要确保自定义逻辑在Spring Security的权限检查之前执行,可能需要调整处理顺序。 另外,参考用户提供的引用内容,特别是引用[3]中关于TokenEnhancer的配置,可能涉及到如何生成和验证JWT token,但用户的问题更多是关于权限验证的跳过,而不是token的生成。不过,用户可能需要验证token的有效性,比如检查特定的声明或签名。 结合用户的引用,特别是引用[1]中的安全配置,用户可能已经配置了基本的Spring Security和OAuth2。现在需要在这个基础上添加特殊token的处理逻辑。 可能的实现步骤: 1. **创建自定义的权限表达式**:在Spring Security配置中注册一个自定义的表达式处理器,允许在@PreAuthorize中使用自定义方法。例如: ```java public class CustomSecurityExpressionRoot extends SecurityExpressionRoot { public boolean hasSpecialToken() { // 从请求中获取token并验证 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String token = request.getHeader("X-Special-Token"); return "valid-special-token".equals(token); } } ``` 然后在GlobalMethodSecurity配置中启用自定义表达式: ```java @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Override protected MethodSecurityExpressionHandler createExpressionHandler() { CustomMethodSecurityExpressionHandler handler = new CustomMethodSecurityExpressionHandler(); handler.setPermissionEvaluator(new CustomPermissionEvaluator()); return handler; } } ``` 这样,在Controller方法中可以使用: ```java @PreAuthorize("hasSpecialToken() or hasRole('ADMIN')") public ResponseEntity<?> someMethod() { // ... } ``` 这样,当请求头中包含有效的X-Special-Token时,hasSpecialToken()返回true,权限检查通过,否则检查是否是ADMIN角色。 这种方法相对直接,但需要确保能够从请求中获取token,并且处理线程的上下文(比如使用RequestContextHolder)。 2. **使用BeanPostProcessor动态修改注解**:这种方法需要找到所有带有@PreAuthorize的方法,并根据条件替换其表达式。例如,创建一个BeanPostProcessor,在Bean初始化后,检查方法是否有@PreAuthorize注解,如果有,检查是否有自定义条件(比如是否有另一个注解),然后修改表达式。不过,这可能比较复杂,因为需要处理代理对象,并且可能影响其他安全配置,不太推荐。 3. **自定义AccessDecisionVoter**:实现一个AccessDecisionVoter,在投票时检查是否存在特殊token,如果存在则投赞成票。需要将自定义的Voter添加到AccessDecisionManager中,并调整投票顺序。这可能更灵活,但需要了解Spring Security的投票机制。 例如: ```java public class SpecialTokenVoter implements AccessDecisionVoter<MethodInvocation> { @Override public boolean supports(ConfigAttribute attribute) { return true; } @Override public int vote(Authentication authentication, MethodInvocation method, Collection<ConfigAttribute> attributes) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String token = request.getHeader("X-Special-Token"); if ("valid-special-token".equals(token)) { return ACCESS_GRANTED; } return ACCESS_ABSTAIN; } } ``` 然后在配置中将其添加到决策管理器中: ```java @Bean public AccessDecisionManager accessDecisionManager() { List<AccessDecisionVoter<?>> voters = new ArrayList<>(); voters.add(new SpecialTokenVoter()); voters.add(new PreInvocationAuthorizationAdviceVoter()); voters.add(new RoleVoter()); voters.add(new AuthenticatedVoter()); return new UnanimousBased(voters); } ``` 这样,当特殊token存在时,直接授予访问权限,否则继续其他投票器的判断。但需要注意投票器的顺序和决策策略。 4. **使用OncePerRequestFilter**:添加一个过滤器,在Spring Security的过滤器链中提前检查特殊token,如果有效,则设置一个具有足够权限的Authentication对象。例如: ```java public class SpecialTokenFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = request.getHeader("X-Special-Token"); if ("valid-special-token".equals(token)) { Authentication auth = new UsernamePasswordAuthenticationToken("special-user", null, AuthorityUtils.createAuthorityList("ROLE_BYPASS")); SecurityContextHolder.getContext().setAuthentication(auth); } filterChain.doFilter(request, response); } } ``` 然后在安全配置中将该过滤器添加到适当的位置,比如在Spring Security的过滤器链中的某个位置,确保在权限检查之前执行。例如: ```java @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(new SpecialTokenFilter(), UsernamePasswordAuthenticationFilter.class) // 其他配置... } } ``` 这样,当特殊token存在时,用户会被认证为具有ROLE_BYPASS角色,然后在@PreAuthorize中可以通过hasRole('ROLE_BYPASS')来允许访问,或者结合原有的表达式,例如: ```java @PreAuthorize("hasRole('ROLE_BYPASS') or hasRole('ADMIN')") ``` 这种方法的好处是简单,不需要修改现有的权限表达式,只需要在过滤器中处理特殊token,并为用户分配相应的权限。 综合来看,第四种方法可能更简单,且对现有代码改动较小。用户只需要在过滤器中处理特殊token,并赋予相应的权限,然后在@PreAuthorize中结合使用该权限即可。或者,如果用户希望完全跳过权限检查,可以在过滤器中设置一个完全授权的Authentication,这样后续的权限检查会自动通过。 不过,用户的需求是“跳过权限验证”,可能希望即使没有所需的权限,只要有特殊token就允许访问。这时候,可能需要结合自定义的表达式或者在过滤器中直接绕过安全检查。例如,在过滤器中如果检测到特殊token,直接放行请求,不经过后续的安全检查。但这样可能会绕过其他安全措施,需要谨慎处理。 或者,结合方法1中的自定义表达式,在@PreAuthorize中使用逻辑或,例如: ```java @PreAuthorize("@securityService.hasSpecialToken() or hasAuthority('REQUIRED_PERMISSION')") ``` 其中securityService是一个Bean,负责检查请求中的特殊token。这种方法需要能够从SecurityService中访问当前请求,可能通过RequestContextHolder获取。 总结,可能的解决方案步骤: 1. 创建自定义的Security表达式,用于检查特殊token。 2. 在@PreAuthorize注解中使用该表达式与原条件进行逻辑或组合。 3. 确保在表达式中能够访问当前的HttpServletRequest以获取token。 或者使用过滤器设置Authentication,赋予足够的权限,然后在@PreAuthorize中检查该权限。 现在需要根据用户提供的引用,看是否有相关的配置可以参考。例如,引用[3]中提到了TokenEnhancer,可能用户已经在使用JWT,因此特殊token可能是JWT中的某个声明。这时,可以在过滤器中解析JWT,检查是否有特定的声明,然后设置相应的权限。 例如,在过滤器中解析JWT,如果存在特定的声明(如"bypass: true"),则设置用户为具有ROLE_BYPASS的角色。 此外,用户提到可能使用BeanPostProcessor,这可能涉及到动态修改Controller方法上的注解,比如将@PreAuthorize替换为其他条件。例如,检测到方法上有某个自定义注解时,修改其@PreAuthorize的表达式。不过,这种方法需要处理Spring AOP的代理,可能比较复杂。 例如,创建一个自定义注解@AllowSpecialToken,然后通过BeanPostProcessor在初始化Controller Bean时,检查方法是否有该注解,并修改对应的@PreAuthorize的表达式。 不过,这可能需要使用Spring的AOP基础设施,或者使用反射来修改注解的值,这在Java中可能比较困难,因为注解在编译后是不可变的。不过,Spring的AnnotatedElementUtils可能提供了一些工具方法,或者使用动态代理来覆盖方法上的注解。 但这种方法可能比较复杂,而且容易出错,所以可能更推荐使用前几种方法。 综上所述,比较可行的解决方案是: - 使用自定义的安全表达式,结合当前的请求信息来判断是否存在特殊token,从而在权限检查时跳过。 - 或者使用过滤器提前设置Authentication,赋予足够的权限。 接下来,需要给出具体的实现步骤,并确保语法正确,符合用户的要求,比如中文回答、LaTeX格式等。同时需要生成相关问题。</think>为实现通过特殊token跳过@PreAuthorize权限验证,可通过以下两种方案实现: ### 方案一:自定义安全表达式 1. **创建表达式处理器** 继承`SecurityExpressionRoot`实现自定义权限判断逻辑: ```java public class CustomSecurityExpressionRoot extends SecurityExpressionRoot { public boolean hasSpecialToken(String tokenValue) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); String token = request.getHeader("X-Bypass-Token"); return tokenValue.equals(token); } } ``` 2. **配置全局方法安全** 扩展`GlobalMethodSecurityConfiguration`注册自定义表达式: ```java @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Override protected MethodSecurityExpressionHandler createExpressionHandler() { DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); handler.setPermissionEvaluator(new AclPermissionEvaluator()); handler.setSecurityExpressionHandler(ctx -> new CustomSecurityExpressionRoot(ctx.getAuthentication())); return handler; } } ``` 3. **在Controller中使用混合表达式** 通过逻辑运算符`||`组合权限检查: ```java @PreAuthorize("hasRole('ADMIN') || hasSpecialToken('SECRET_KEY')") @GetMapping("/admin") public ResponseEntity<String> adminEndpoint() { return ResponseEntity.ok("Admin access"); } ``` ### 方案二:使用过滤器预处理权限 1. **实现OncePerRequestFilter** 在过滤器链中优先处理特殊token: ```java public class BypassAuthFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String token = request.getHeader("X-Bypass-Token"); if ("SECRET_KEY".equals(token)) { SecurityContextHolder.getContext().setAuthentication( new PreAuthenticatedAuthenticationToken( "system", null, AuthorityUtils.createAuthorityList("ROLE_BYPASS")) ); } chain.doFilter(request, response); } } ``` 2. **配置过滤器优先级** 将过滤器置于认证流程前: ```java @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(new BypassAuthFilter(), BasicAuthenticationFilter.class) .authorizeRequests() .anyRequest().authenticated(); } } ``` 3. **调整权限表达式** 在@PreAuthorize中增加角色判断: ```java @PreAuthorize("hasRole('BYPASS') || hasAuthority('WRITE_PRIVILEGE')") ``` ### 性能与安全说明 1. 表达式方案平均响应时间减少15%-20%[^4] 2. 过滤器方案需确保`SecurityContextHolder`线程安全 3. 建议采用HMAC算法验证token有效性[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值