authorize(基于注解的权限认证框架)

一、是什么

很多项目都会用到权限管理,目前流行的权限框架(Apache Shiro,Spring Security等)在使用的时候都觉得很繁琐,特别是在一些小型的项目中。有时候我会想,如果通过注解的方式,直接把权限注解到访问的接口方法上那该有多好。
authorize就是一个为了解决这个问题,通过注解配置权限,借助拦截器进行权限检查的一个开源权限框架。使用起来就像下面这种感觉。

@Access("manage")
@RequestMapping("index")
public String index() {
    return "this is index page";
}

@Access是这个框架的注解。通过注解配置权限的方式,解决权限认证的问题,不管是写代码还是读代码,都感觉更清晰了许多。

二、如何用

2.1 快速使用

可以参照示例authorize-demo

2.1.1 引入maven依赖

<dependency>
    <groupId>com.github.sunbufu</groupId>
    <artifactId>authorize-starter</artifactId>
    <version>1.0.0-RELEASE</version>
</dependency>

2.1.2 实现IAuthorizeService

IAuthorizeService的实现类中,至少应该实现3个方法:

  1. 登录方法:登录成功后,把用户信息存放到session
  2. 鉴权方法(authorize):通过比对用户和请求方法的权限,返回该用户是否可以访问
  3. 鉴权失败方法(authorizeFail):用户没有权限时,需要进行的处理方法

登录:

public User logIn(String userName, String passWord, HttpSession session) {
    User user = users.get(userName);
    if (!user.getPassWord().equals(passWord)) {
        return null;
    }
    session.setAttribute(USER_SESSION_KEY, user);
    return user;
}

鉴权:

@Override
public boolean authorize(String[] access, HttpSession session) {
    User user = (User) session.getAttribute(USER_SESSION_KEY);
    if (user != null && user.getAccess() != null && user.getAccess().isEmpty()) {
        for (String requestAccess : access) {
            if (user.getAccess().contains(requestAccess)) {
                return true;
            }
        }
    }
    return false;
}

鉴权失败:

@Override
public void authorizeFail(HttpServletRequest request, HttpServletResponse response) {
    response.sendRedirect("authorizeError?message=your account have not enought authority");
}

2.1.3 通过注解配置到controller

@Access("manage")
@RequestMapping("index")
public String index() {
    return "this is index page";
}

2.1.4 完成

authorize的目的是借助注解,快速的完成一些简单的权限管理功能,所以从使用到配置上力争尽量的简单、快捷。
完整示例地址authorize-demo

2.2 框架介绍

authorize框架主要包括authorize-coreauthorize-starter

2.2.1 authorize-core

authorize-core是整个框架的核心和主要的逻辑部分,主要包括注解Access、拦截器AccessInterceptor、权限认证接口IAuthorizeService

  1. IAuthorizeService主要包括3个方法的声明,其中有2个方法必须实现:authorize(鉴权)和authorizeFail(鉴权失败),1个方法选择实现:authorizeSuccess(鉴权成功)。
  2. AccessInterceptor会拦截所有的请求,并对注解@Access的进行鉴权。首先会把注解在controller上的权限和注解在具体方法上的权限合并,然后调用IAuthorizeService实现类的鉴权方法authorize。成功调用authorizeSuccess(鉴权成功),失败则调用authorizeFail(鉴权失败)。

2.2.2 authorize-starter

authorize-starter是为spring boot提供的一个快速配置。主要是配置了authorize-core的拦截器AccessInterceptor

三、总结

authorize是为了快速便捷进行权限管理的开源框架,在github上开源地址是https://github.com/sunbufu/sunbufu-authorize。欢迎大家关注、加星,也欢迎大家随时联系我sunyoubufu@qq.com,谢谢。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,我无法直接为您生成代码。但是,我可以为您提供一些指导,以便您开始使用Spring Security框架来实现PBAC模型。 首先,您需要了解什么是PBAC模型。 PBAC(基于角色的访问控制)是一种访问控制模型,其中用户的访问权限由其角色确定。因此,PBAC模型可以表示为具有以下组成部分的权限系统: 1. 用户 2. 角色 3. 权限 4. 资源 在Spring Security中,您可以使用以下组件来实现PBAC模型: 1. Authentication(认证) 2. Authorization(授权) 3. Access Control(访问控制) 下面是一个简单的示例,演示如何使用Spring Security框架实现基于角色的访问控制。 1. 配置授权规则: ```java @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin").roles("ADMIN") .and() .withUser("user").password("{noop}user").roles("USER"); } } ``` 在这个例子中,我们定义了两个用户角色:ADMIN和USER。ADMIN用户可以访问“/admin/**”路径,而USER用户可以访问“/user/**”路径。任何其他请求都需要进行身份验证才能访问。 2. 创建自定义AccessDecisionVoter: ```java public class PbcaAccessDecisionVoter implements AccessDecisionVoter<Object> { @Override public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) { if (authentication == null) { return ACCESS_DENIED; } int result = ACCESS_ABSTAIN; for (ConfigAttribute attribute : configAttributes) { if (this.supports(attribute)) { result = ACCESS_DENIED; List<GrantedAuthority> authorities = (List<GrantedAuthority>) authentication.getAuthorities(); for (GrantedAuthority authority : authorities) { if (attribute.getAttribute().equals(authority.getAuthority())) { return ACCESS_GRANTED; } } } } return result; } @Override public boolean supports(ConfigAttribute attribute) { return attribute.getAttribute() != null; } @Override public boolean supports(Class<?> clazz) { return true; } } ``` 这个自定义的AccessDecisionVoter实现了AccessDecisionVoter接口,并重写了其中的vote()、supports()和supports()方法。这个自定义的AccessDecisionVoter用于根据用户的角色来决定是否允许访问资源。 3. 配置AccessDecisionManager: ```java @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Override protected AccessDecisionManager accessDecisionManager() { List<AccessDecisionVoter<? extends Object>> decisionVoters = Arrays.asList(new PbcaAccessDecisionVoter()); return new AffirmativeBased(decisionVoters); } } ``` 在这个例子中,我们定义了一个方法级别的安全配置,并通过@EnableGlobalMethodSecurity注解启用了prePostEnabled选项。我们还配置了一个AccessDecisionManager,该Manager使用我们之前定义的自定义AccessDecisionVoter来做出访问决策。 这是一个简单的示例,演示如何使用Spring Security框架实现基于角色的访问控制。当然,您需要根据您的需求进行更改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值