forked from xkcoding/spring-boot-demo
-
Notifications
You must be signed in to change notification settings - Fork 37
/
AuthController.java
72 lines (63 loc) · 2.56 KB
/
AuthController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.xkcoding.rbac.security.controller;
import com.xkcoding.rbac.security.common.ApiResponse;
import com.xkcoding.rbac.security.common.Status;
import com.xkcoding.rbac.security.exception.SecurityException;
import com.xkcoding.rbac.security.payload.LoginRequest;
import com.xkcoding.rbac.security.util.JwtUtil;
import com.xkcoding.rbac.security.vo.JwtResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
/**
* <p>
* 认证 Controller,包括用户注册,用户登录请求
* </p>
*
* @package: com.xkcoding.rbac.security.controller
* @description: 认证 Controller,包括用户注册,用户登录请求
* @author: yangkai.shen
* @date: Created in 2018-12-07 17:23
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtUtil jwtUtil;
/**
* 登录
*/
@PostMapping("/login")
public ApiResponse login(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsernameOrEmailOrPhone(), loginRequest.getPassword()));
SecurityContextHolder.getContext()
.setAuthentication(authentication);
String jwt = jwtUtil.createJWT(authentication,loginRequest.getRememberMe());
return ApiResponse.ofSuccess(new JwtResponse(jwt));
}
@PostMapping("/logout")
public ApiResponse logout(HttpServletRequest request) {
try {
// 设置JWT过期
jwtUtil.invalidateJWT(request);
} catch (SecurityException e) {
throw new SecurityException(Status.UNAUTHORIZED);
}
return ApiResponse.ofStatus(Status.LOGOUT);
}
}