介绍活动链接:https://github.com/weopenproj...马拉古的认证授权参考spring-security思想。详情请移步官方文档。malagu除了提供基本的安全性外,还提供了ODIC认证和OAuth2.0授权能力。本文主要介绍@malagu/security组件的基本应用实践。认证授权组件@malagu/security的简单应用1.在项目中添加组件引用@malagu/security组件yarnadd@malagu/security#ornpmi@malagu/security2.重写loginUrl和logoutUrl定义登录和注销接口和请求方法malagu:security:loginUrl:/api/loginloginMethod:POSTlogoutUrl:/api/logout3.重写UserService实现自定义登录。注册用户时需要通过PasswordEncoder生成密码;我们只需要将用户和密码在load()中赋值给安全组件User即可,验证比对逻辑由@malagu/security组件完成。从'@malagu/core'导入{Component,Autowired};从'@malagu/security/lib/node'导入{UserService,UsernameNotFoundError,AccountStatusError,PasswordEncoder};从'@malagu导入{User,ElPolicy,PolicyType,AuthorizeType}/security';import{OrmContext,Transactional}from"@malagu/typeorm/lib/node";import{UserEntity}from'@microservice/datasource';/***重写UserService实现自定义登录*@paramusername登录名称可以是用户名(user_name)或电话(mobile),优先级:user_name>mobile*/@Component({id:UserService,rebind:true})exportclassUserServiceImplimplementsUserService{@Autowired(PasswordEncoder)protectedreadonlypasswordEncoder:PasswordEncoder;@Transactional({readOnly:true})asyncload(username:string):Promise{constrepo=OrmContext.getRepository(UserEntity);letuser=awaitrepo.findOne({userName:username})if(!user){user=awaitrepo.findOne({mobile:username})}if(!user){thrownewUsernameNotFoundError();}if(user.state==false){thrownewAccountStatusError();}return{type:"",username:user.userName,password:user.password,policies:[{type:PolicyType.el,authorizeType:AuthorizeType.Pre,el:'true'}],accountNonExpired:true,accountNonLocked:true,credentialsNonExpired:true,enabled:true}}}4.重写认证丢失处理器AuthenticationErrorHandlerimport{Component,Autowired}from'@malagu/core';import{HttpStatus}from'@malagu/web';import{ErrorHandler,Context,RedirectStrategy}from'@malagu/web/lib/node';import{AuthenticationErrorHandler,AUTHENTICATION_ERROR_HANDLER_PRIORITY,AuthenticationError}来自'@malagu/security/lib/node'@Component({id:AuthenticationErrorHandler,rebind:true})导出类AuthenticationErrorHandlerImpl实现ErrorHandler{readonlypriority:number=AUTHENTICATION_ERROR_HANDLER_PRIORITY;@Autowired(RedirectStrategy)protectedreadonlyredirectStrategy:RedirectStrategy;canHandle(ctx:Context,err:Error):Promise{returnPromise.resolve(errinstanceofAuthenticationError);}asynchandle(ctx:Context,err:AuthenticationError):Promise{letmessage="";switch(err.name){case"UsernameNotFoundError":ctx.response.statusCode=HttpStatus.FORBIDDEN;message="用户不存在";休息;案例“BadCredentialsError”:ctx.response.statusCode=HttpStatus.FORBIDDEN;message="用户密码错误";休息;案例“AccountStatusError”:ctx.response.statusCode=HttpStatus.FORBIDDEN;message="用户被冻结";休息;案例“AuthenticationError”:ctx.response.statusCode=HttpStatus.UNAUTHORIZED;message="用户没有访问权限,需要进行身份验证";休息;默认值:ctx.response.statusCode=HttpStatus.UNAUTHORIZED;消息=错误消息;休息;}ctx.response.end(消息);}}5.重写认证成功handlerAuthenticationSuccessHandler不需要重写,不重写会跳转到首页import{Component}from'@malagu/core';import{HttpStatus}from'@malagu/web';import{AuthenticationSuccessHandler,Authentication}from'@malagu/security/lib/node'import{Context}from'@malagu/web/lib/node'@Component({id:AuthenticationSuccessHandler,rebind:true})exportclassAuthenticationSuccessHandlerImplimplementsAuthenticationSuccessHandler{异步onAuthenticationSuccess(身份验证:身份验证):Promise{Context.getResponse().statusCode=HttpStatus.OK;Context.getResponse().body=JSON.stringify({username:authentication.name});}}6.再次注销ProcessorLogoutSuccessHandler不需要,如果不重写,会跳转到登录页面/core';import{HttpStatus}from'@malagu/web';import{Context}from'@malagu/web/lib/node';@Component({id:LogoutSuccessHandler,rebind:true})exportclassLogoutSuccessHandlerImpl实现LogoutSuccessHandler{readonlypriority=LOGOUT_SUCCESS_HANDLER_PRIORITY;SucconLogout():Promise{Context.getResponse().statusCode=HttpStatus.OK;Context.getResponse().body="注销成功";}}7.@Authenticated的使用可以用在controller类上,这样类下所有开放的接口都需要认证@Controller("user")@Authenticated()exportclassUserController{@Autowired(UserInfoService)受保护的userInfoService:UserInfoService;......}也可以在指定接口上使用@Get("/:userId")@Json()@Authenticated()asyncgetUserInfo(@Param("userId")userId:number){constresult=等待this.userInfoService.getUserInfo(userId);returnresult}8.malagu除了@Authenticated之外,还提供了装饰器@PreAuthorize和匿名@Anonymous用于权限控制,至此,@malagu/security的核心代码已经在module.ts文件中引用,我们可以通过以下方式进行调试运行项目。由于登录逻辑由组件处理,所以malagu的认证授权相对简单。考虑@malagu/security的理由是什么?UserService中User的各个属性是什么意思?如何设置登录有效期?使用@malagu/security可以实现单点登录吗?本文为学习文章,如有错误请指正!思考的内容欢迎大家答疑解惑。