本文主要向大家介绍了登录鉴权-JAVA语言,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
登录鉴权:
1. 用户名+密码 登录请求
2. 后台接收登录请求,生成ToKen(用户名/密码正确) 返回token
3. 请求其他api 都带上token,后台校验token是否存在/过期
后台代码如下:
登录/登出 --------------
@RestController
@RequestMapping
class AuthController {
@Autowired
private lateinit var tokenService: TokenService
@Autowired
private lateinit var appUserService: AppUserService
@PostMapping(value = ["/auth/login"])
fun login(username: String, password: String,
request: HttpServletRequest): RestResponse {
val predicate = Predicate.eq("username", username).eq("password", password)
val user = appUserService.findOne(predicate) ?: return RestResponse(1, "用户不存在")
// 生成一个 token,保存用户登录状态
val tokenModel = tokenService.createToken(user.userId, user.nickname, Utils.getIp(request))
return RestResponse(0, mapOf(
"user" to user,
"token" to tokenModel.token,
"roles" to arrayOf("admin")))
}
@PostMapping(value = ["/auth/logout"])
fun logout(@RequestAttribute tokenModel: TokenModel): RestResponse {
tokenService.deleteToken(tokenModel.token)
return RestResponse(0, "success")
}
}
-----配置拦截器---------------------------
WebAppConfigurer.kt
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(authInterceptor())
.excludePathPatterns("/auth/**")
.excludePathPatterns("/rest/**")
}
@Bean
fun authInterceptor(): AuthInterceptor {
return AuthInterceptor()
}
拦截器-------------------------------
@Component
class AuthInterceptor : HandlerInterceptorAdapter() {
@Autowired
private lateinit var tokenService: TokenService
@Throws(Exception::class)
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
//从header中得到token
val token = request.getHeader("x-token")
//验证token
val tokenModel = tokenService.checkToken(token)
if (tokenModel != null) {
//如果token验证成功,将token对应的用户id存在request中,便于之后注入
request.setAttribute("tokenModel", tokenModel)
return true
}
//如果验证token失败,返回401错误
response.status = HttpServletResponse.SC_UNAUTHORIZED
return false
}
}
以上就是职坐标整理发布关于JAVA的介绍,先祝大家对它有了一定的了解吧,了解更多内容,请关注职坐标编程语言JAVA频道!