添加组件
@malagu/security
默认配置
malagu:security:enabled: trueusernameKey: usernamepasswordKey: passwordbackend:malagu:security:contextKey: malagu:securityContextusername: adminpassword: MzQ0NTg4ZTk2NzQyYWI1ODA1MDFlNDBjMzZhZDY4OWQ1Zjc5ZDYxYzc2MjQ1NWZk # raw password 123456passwordEncoder:secret: 123456encodeHashAsBase64: truebasic:realm: realmloginPage: /loginloginUrl: /loginloginMethod: POSTloginSuccessUrl: /logoutUrl: /logoutlogoutMethod: POSTlogoutSuccessUrl: /login
实现登录页面
在登录页面中,通过 POST 请求提交用户名(username)和密码(password)到 /login ,将会触发框架的认证流程,默认提供的用户名为:admin,密码为:123456,当然,您也可以实现 UserStore 接口提供您自己用户信息。当用户名和密码都匹配成功后,则认证成功,跳转到登录成功页面,默认是 / ,否则认证失败,跳转到登录页面 /login 。
自定义 UserStore
您可以通过查询数据库获取用户信息,以下为框架默认实现,返回固定的用户信息:
@Component(UserStore)export class UserStoreImpl implements UserStore {@Value('malagu.security')protected readonly options: any;async load(username: string): Promise<User> {if (this.options.username === username) {return {username,password: this.options.password,accountNonExpired: true,accountNonLocked: true,credentialsNonExpired: true,enabled: true,policies: [ <ElPolicy>{type: PolicyType.El,authorizeType: AuthorizeType.Pre,el: 'true'} ]};}throw new UsernameNotFoundError(`Could not find: ${username}`);}}
方法保护
默认对外的方法都会保护起来,当您没有登录通过 ajax 直接方法,将返回 401 状态码;当您没有登录通过浏览器访问页面,将返回 302 状态码,重定向到登录页面。
登录成功后,当您有权限访问该方法,则访问成功,当您没有权限访问该方法,则访问失败,返回 403 状态码。
匿名访问
方法上添加装饰器 @Anonymous ,可以让方法可以匿名访问。
@Get()@Anonymous()@Transactional({ readOnly: true })list(): Promise<User[]> {const repo = OrmContext.getRepository(User);return repo.find();}
 
也可以添加到类上,让类的所有方法可以里面访问。
@Controller('users')@Anonymous()export class UserController {...}
授权
任何方法或者页面都需要显示授权才能访问,单单认证通过是不够的,可以授权给用户访问某些方法的权限,也可以授权给方法,允许哪类用户可以访问。框架会更加这些权限信息做权限验证,验证通过了才可以访问具体的方法和页面,后面会做详细的展开
