123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package com.yaozhitech.spring5.controller;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.subject.Subject;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RestController;
- import com.yaozhitech.spring5.dto.UserDto;
- import com.yaozhitech.spring5.service.UserService;
- import lombok.extern.slf4j.Slf4j;
- import reactor.core.publisher.Mono;
- @Slf4j
- @RestController
- public class LoginController {
- @Autowired
- private UserService userService;
- /**
- * 用户名密码登录
- *
- * @param request
- * @return token
- */
- @PostMapping(value = "/login")
- public ResponseEntity<Mono<UserDto>> login(@RequestBody UserDto loginInfo, HttpServletResponse response) {
- Subject subject = SecurityUtils.getSubject();
- try {
- UsernamePasswordToken token = new UsernamePasswordToken(loginInfo.getUsername(), loginInfo.getPassword());
- subject.login(token);
- UserDto user = (UserDto) subject.getPrincipal();
-
- Mono<UserDto> userMono = Mono.just(user).map(u -> {return userService.generateJwtToken(user.getUsername());})
- .doOnNext(u -> {response.setHeader("x-auth-token", u);})
- .map(u -> {return userService.getJwtTokenInfo(loginInfo.getUsername());});
-
- return ResponseEntity.ok(userMono);
- } catch (AuthenticationException e) {
- log.error("User {} login fail, Reason:{}", loginInfo.getUsername(), e.getMessage());
- return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
- } catch (Exception e) {
- return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
- }
- }
- /**
- * 退出登录
- *
- * @return
- */
- @GetMapping(value = "/logout")
- public Mono<String> logout() {
- Subject subject = SecurityUtils.getSubject();
- if (subject.getPrincipals() != null) {
- }
- SecurityUtils.getSubject().logout();
- return Mono.empty();
- }
-
- }
|