|
| 1 | +package top.cadecode.uniboot.controller; |
| 2 | + |
| 3 | +import cn.hutool.http.HttpResponse; |
| 4 | +import cn.hutool.http.HttpUtil; |
| 5 | +import io.swagger.annotations.Api; |
| 6 | +import io.swagger.annotations.ApiOperation; |
| 7 | +import lombok.RequiredArgsConstructor; |
| 8 | +import lombok.extern.slf4j.Slf4j; |
| 9 | +import org.springframework.web.bind.annotation.PostMapping; |
| 10 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 11 | +import org.springframework.web.bind.annotation.RequestParam; |
| 12 | +import org.springframework.web.bind.annotation.RestController; |
| 13 | +import top.cadecode.uniboot.common.annotation.ApiFormat; |
| 14 | +import top.cadecode.uniboot.common.response.ApiResult; |
| 15 | +import top.cadecode.uniboot.common.util.JacksonUtil; |
| 16 | +import top.cadecode.uniboot.framework.config.SecurityConfig; |
| 17 | +import top.cadecode.uniboot.framework.security.TokenAuthHolder; |
| 18 | + |
| 19 | +import javax.servlet.http.HttpServletRequest; |
| 20 | +import javax.servlet.http.HttpServletResponse; |
| 21 | + |
| 22 | +/** |
| 23 | + * 认证API |
| 24 | + * |
| 25 | + * @author Cade Li |
| 26 | + * @since 2023/4/9 |
| 27 | + */ |
| 28 | +@ApiFormat |
| 29 | +@Slf4j |
| 30 | +@RequiredArgsConstructor |
| 31 | +@Api(tags = "认证API") |
| 32 | +@RestController |
| 33 | +@RequestMapping("auth") |
| 34 | +public class AuthController { |
| 35 | + |
| 36 | + private final TokenAuthHolder tokenAuthHolder; |
| 37 | + |
| 38 | + /** |
| 39 | + * 复用Security login接口,方便swagger展示 |
| 40 | + */ |
| 41 | + @ApiOperation("登录") |
| 42 | + @PostMapping("login") |
| 43 | + public ApiResult<?> login(HttpServletRequest request, HttpServletResponse response, |
| 44 | + @RequestParam String username, @RequestParam String password) { |
| 45 | + String replacedURL = request.getRequestURL().toString().replace("/auth/login", SecurityConfig.LOGIN_URL); |
| 46 | + HttpResponse loginRes = HttpUtil.createPost(replacedURL) |
| 47 | + .form(SecurityConfig.USERNAME_PARAMETER, username) |
| 48 | + .form(SecurityConfig.PASSWORD_PARAMETER, password) |
| 49 | + .execute(); |
| 50 | + response.addHeader(tokenAuthHolder.getHeader(), loginRes.header(tokenAuthHolder.getHeader())); |
| 51 | + return JacksonUtil.toBean(loginRes.body(), ApiResult.class); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * 复用Security logout接口,方便swagger展示 |
| 56 | + */ |
| 57 | + @ApiOperation("注销") |
| 58 | + @PostMapping("logout") |
| 59 | + public ApiResult<?> login(HttpServletRequest request, HttpServletResponse response) { |
| 60 | + String replacedURL = request.getRequestURL().toString().replace("/auth/logout", SecurityConfig.LOGOUT_URL); |
| 61 | + HttpResponse loginRes = HttpUtil.createPost(replacedURL) |
| 62 | + .header(tokenAuthHolder.getHeader(), request.getHeader(tokenAuthHolder.getHeader())) |
| 63 | + .execute(); |
| 64 | + return JacksonUtil.toBean(loginRes.body(), ApiResult.class); |
| 65 | + } |
| 66 | +} |
0 commit comments