diboot/diboot-docs/guide/diboot-iam/开始使用.md

3.8 KiB
Raw Permalink Blame History

IAM-base 使用说明

1、引入依赖

Gradle:

compile("com.diboot:diboot-iam-base-spring-boot-starter:{latestVersion}")

或Maven

<dependency>
    <groupId>com.diboot</groupId>
    <artifactId>diboot-iam-base-spring-boot-starter</artifactId>
    <version>{latestVersion}</version>
</dependency>

配置了数据库连接初次启动时iam-base starter组件会自初始化生成相关的表及初始数据。

如果使用diboot-devtools还需要引入devtools相关依赖可一键生成iam-base相关的controller。

2、参数配置

  • 注解配置: 请确保您的启动类或者配置类上配置了**@EnableTransactionManagement**注解,如:
@EnableTransactionManagement
@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}
  • 配置文件配置项:

#JWT的签名key需自定义
diboot.iam.jwt-signkey=xxx
#JWT的token过期时间默认为60分钟
diboot.iam.jwt-token-expires-minutes=60

#Shiro的匿名urls用逗号分隔
diboot.iam.anon-urls=/test/**,/abc/**

#是否开启权限检查默认true。改为false后结合anno-urls=/**配置,可忽略权限检查,便于开发环境调试
diboot.iam.enable-permission-check=true

#缓存实现类,默认为: org.apache.shiro.cache.MemoryConstrainedCacheManager
diboot.iam.cache-manager-class=org.apache.shiro.cache.MemoryConstrainedCacheManager

IAM-base组件

3、认证与授权

  • 登录/申请token后端:
PwdCredential credential = new PwdCredential("admin", "123456"); //默认预置管理员的账号密码
String authtoken = AuthServiceFactory.getAuthService(Cons.DICTCODE_AUTH_TYPE.PWD.name()).applyToken(credential);
  • 前端登录拿到token后缓存并将其加入每次请求的header中属性名为: authtoken

  • 当token的有效期剩余不足1/4时组件会自动生成新的token写入response的header中属性名同样为: authtoken。 前端检查response的header如果有新的authtoken则替换本地的缓存值。

4、BindPermission注解使用

  • 支持在Controller的类及方法上添加权限识别码支持类似Spring @RequestMapping注解的“类+方法”拼接功能, 方法上的注解支持自动鉴权,同时可被继承。如:
@RequestMapping("/user")
@BindPermission(name = "用户") // code可选,默认自动识别; sortId可选
//继承类支持自动识别code为当前entity类名"IamUser"
public class IamUserController extends BaseCrudMappingRestController<IamUser, IamUserVO> {
    @GetMapping("/test")
    @BindPermission(name = "自定义", code = "test") // 拼接后的code=IamUser:test
    // 以上注解支持自动鉴权,与 @RequiresPermissions(values={"IamUser:test"}) 等效,省掉前缀以简化及继承。
    public JsonResult custom(){
    }
}
    • BindPermission注解支持自动提取需要认证的接口列表提供给前端进行快捷绑定。

5、登录/注册/退出

  • 登录:
// PwdCredential credential = ...; // 登录页提交账号密码认证凭证
String authtoken = AuthServiceFactory.getAuthService(Cons.DICTCODE_AUTH_TYPE.PWD.name()).applyToken(credential);
return new JsonResult(authtoken);
  • 退出:
IamSecurityUtils.logout();
  • 注册账号
IamAccount account = new IamAccount();// 创建账号
... 
iamAccountService.createEntity(account);
  • 获取当前用户对象:
IamUser currentUser = IamSecurityUtils.getCurrentUser();
// 多种类型的用户
BaseLoginUser loginUser = IamSecurityUtils.getCurrentUser();
// 转型

6、样例参考 - diboot-iam-example

使用过程中遇到问题,可加群交流。