数据库相关
This commit is contained in:
parent
881c556f6a
commit
e9ac9d5f99
8
pom.xml
8
pom.xml
|
|
@ -17,13 +17,17 @@
|
|||
|
||||
<properties>
|
||||
<!-- 指定编译使用的 Java 版本 -->
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
<!-- 可选:指定编译编码 -->
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/login", "/css/**", "/js/**", "/img/**", "/libs/**", "/captcha", "/toAuth",
|
||||
.antMatchers("/login", "/css/**", "/js/**", "/img/**", "/libs/**", "/captcha", "/toAuth","/redirect",
|
||||
"/ws", "/swagger-ui.html",
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs",
|
||||
|
|
|
|||
|
|
@ -1,25 +1,39 @@
|
|||
package com.hshh.nation.login.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.hshh.nation.advice.GlobalExceptionHandler;
|
||||
import com.hshh.nation.common.BaseController;
|
||||
import com.hshh.nation.common.OperateResult;
|
||||
import com.hshh.nation.advice.GlobalExceptionHandler;
|
||||
import com.hshh.nation.login.model.ExtendUserDetails;
|
||||
import com.hshh.nation.set.service.ConfigService;
|
||||
import com.hshh.nation.user.entity.User;
|
||||
import com.hshh.nation.user.service.UserService;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import lombok.Data;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
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.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Map;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
@Controller
|
||||
@Slf4j
|
||||
|
|
@ -27,31 +41,98 @@ public class LoginController extends BaseController {
|
|||
|
||||
@Resource
|
||||
private ConfigService configService;//全局配置service
|
||||
|
||||
private final WebClient webClient = WebClient.create();
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Value("${third.auth.client_id}")
|
||||
private String clientId;
|
||||
@Value("${third.auth.client_secret}")
|
||||
private String clientSecret;
|
||||
|
||||
@Value("${third.auth.token-url}")
|
||||
private String tokenUrl;
|
||||
@Value("${third.auth.userinfo-url}")
|
||||
private String getUserUrl;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Value("${third.auth.jump_url}")
|
||||
private String jumpUrl;
|
||||
@Value("${third.auth.redirect_url}")
|
||||
private String redirectUrl;
|
||||
@Value("${third.auth.logout_url}")
|
||||
private String logoutUrl;
|
||||
|
||||
//导向到登录页面
|
||||
@RequestMapping("/login")
|
||||
public String loginPage(Model model) {
|
||||
Random random = new Random();
|
||||
|
||||
Map<String, String> setMap = configService.getMapAllSet();
|
||||
|
||||
String url = jumpUrl + "?response_type=code&client_id=" + clientId + "&redirect_uri="
|
||||
+ Base64.getUrlEncoder().encodeToString(redirectUrl.getBytes(StandardCharsets.UTF_8))
|
||||
+ "&active_type=user&state=" + random.nextDouble();
|
||||
log.info("jumpUrl::{}", url);
|
||||
String systemTitle = setMap.get("system.title");
|
||||
model.addAttribute("systemTitle", systemTitle);
|
||||
model.addAttribute("jumpUrl", url);
|
||||
return "login";
|
||||
}
|
||||
|
||||
@GetMapping("/redirect")
|
||||
|
||||
public String redirect(String code, HttpServletRequest request) {
|
||||
//获取token
|
||||
String token = token(code);
|
||||
LoginForm loginForm = getThirdUserAndSaveUserIfNotExit(token);
|
||||
log.info("loginForm::{}", JSON.toJSONString(loginForm));
|
||||
if (loginForm != null) {
|
||||
authLoginForm(loginForm, request);
|
||||
}
|
||||
request.getSession().setAttribute("token", token);
|
||||
return "redirect:/home";
|
||||
}
|
||||
|
||||
@GetMapping("/out")
|
||||
public String logout(HttpServletRequest request) {
|
||||
log.info("logout.....");
|
||||
String token = request.getSession().getAttribute("token") == null ? ""
|
||||
: request.getSession().getAttribute("token").toString();
|
||||
if (StringUtils.isNotBlank(token)) {
|
||||
//回收token
|
||||
String url =
|
||||
logoutUrl + "?client_id=" + clientId + "&client_secret=" + clientSecret + "&access_token="
|
||||
+ token;
|
||||
|
||||
String result = webClient.get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.block();
|
||||
log.info("result::{}", result);
|
||||
if (result != null) {
|
||||
JSONObject jsonObject = JSON.parseObject(result);
|
||||
if (jsonObject.containsKey("code")) {
|
||||
if (jsonObject.getInteger("code") == 200) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
request.getSession().removeAttribute("token");
|
||||
request.getSession().invalidate();
|
||||
return "redirect:/login";
|
||||
}
|
||||
|
||||
//登录
|
||||
@PostMapping("/toAuth")
|
||||
@ResponseBody
|
||||
public OperateResult<String> login(@RequestBody LoginForm loginForm, HttpServletRequest request) {
|
||||
try {
|
||||
log.info("username={}", loginForm.getUsername());
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginForm.getUsername(), loginForm.getPassword());
|
||||
authenticationManager.authenticate(token);
|
||||
Authentication authentication = authenticationManager.authenticate(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
request.getSession().setAttribute("user", authentication.getPrincipal());
|
||||
request.getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
|
||||
authLoginForm(loginForm, request);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
return OperateResult.error(null, e.getMessage(), GlobalExceptionHandler.SERVER_ERROR_CODE);
|
||||
|
|
@ -60,6 +141,18 @@ public class LoginController extends BaseController {
|
|||
return OperateResult.success();
|
||||
}
|
||||
|
||||
private void authLoginForm(LoginForm loginForm, HttpServletRequest request) {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
|
||||
loginForm.getUsername(), loginForm.getPassword());
|
||||
authenticationManager.authenticate(token);
|
||||
Authentication authentication = authenticationManager.authenticate(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
request.getSession().setAttribute("user", authentication.getPrincipal());
|
||||
request.getSession(true)
|
||||
.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
|
||||
SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
@GetMapping("/home")
|
||||
public String home(Model model) {
|
||||
log.info("home");
|
||||
|
|
@ -68,9 +161,86 @@ public class LoginController extends BaseController {
|
|||
model.addAttribute("currentUser", user);
|
||||
return "fragments/layout";
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class LoginForm{
|
||||
public static class LoginForm {
|
||||
|
||||
String username;
|
||||
String password;
|
||||
}
|
||||
|
||||
private String token(String code) {
|
||||
try {
|
||||
String url = tokenUrl + "?client_id=" + clientId + "&client_secret=" + clientSecret
|
||||
+ "&grant_type=authorization_code&code=" + code;
|
||||
log.info("tokenUrl: {}", url);
|
||||
String result = webClient.get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.block();
|
||||
log.info("token: {}", result);
|
||||
JSONObject resultObject = JSON.parseObject(result);
|
||||
if (resultObject != null && resultObject.containsKey("code")) {
|
||||
if (resultObject.getInteger("code") == 200) {
|
||||
return resultObject.getJSONObject("data").getString("access_token");
|
||||
}
|
||||
return resultObject.getString("access_token");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public LoginForm getThirdUserAndSaveUserIfNotExit(String token) {
|
||||
String userUrl = getUserUrl + "?access_token=" + token;
|
||||
log.info("getUserUrl: {}", userUrl);
|
||||
try {
|
||||
String result = webClient.get()
|
||||
.uri(userUrl)
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.block();
|
||||
log.info("getUserUrl result: {}", result);
|
||||
JSONObject resultObject = JSON.parseObject(result);
|
||||
if (resultObject != null && resultObject.containsKey("code")) {
|
||||
if (resultObject.getInteger("code") == 200) {
|
||||
|
||||
User user = getUser(resultObject.getJSONObject("data"));
|
||||
User userInDb = userService.getUserByUserId(user.getUserId());
|
||||
if (userInDb == null) {
|
||||
//插入到数据库
|
||||
User newUser = new User();
|
||||
newUser.setUserId(user.getUserId());
|
||||
newUser.setUserName(user.getUserName());
|
||||
newUser.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
|
||||
newUser.setNickName(user.getNickName());
|
||||
newUser.setSuperFlag(1);
|
||||
userService.save(newUser);
|
||||
}
|
||||
LoginForm loginForm = new LoginForm();
|
||||
loginForm.setUsername(user.getUserName());
|
||||
loginForm.setPassword(user.getPassword());
|
||||
return loginForm;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private User getUser(JSONObject userObject) {
|
||||
User user = new User();
|
||||
user.setUserId(userObject.getString("userId"));
|
||||
user.setUserName(userObject.getString("userName"));
|
||||
user.setNickName(userObject.getString("nickName"));
|
||||
|
||||
user.setPassword(userObject.getString("password"));
|
||||
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.hshh.nation.login.model;
|
||||
|
||||
import com.hshh.nation.menu.entity.Menu;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
|
@ -37,7 +38,7 @@ public class ExtendUserDetails implements UserDetails {
|
|||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return List.of();
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.hshh.nation.user.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import java.io.Serializable;
|
||||
|
|
@ -43,4 +44,6 @@ public class User implements Serializable {
|
|||
* 超级管理员标志.
|
||||
*/
|
||||
private int superFlag;
|
||||
private String userId;
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,4 +19,5 @@ public interface UserService extends IService<User> {
|
|||
* @return 用户对象.
|
||||
*/
|
||||
User getUserByUsername(String username);
|
||||
User getUserByUserId(String userId);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,4 +28,15 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
|||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getUserByUserId(String userId) {
|
||||
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("user_id", userId);
|
||||
List<User> list = this.list(queryWrapper);
|
||||
if (!list.isEmpty()) {
|
||||
return list.get(0);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,14 +17,14 @@ spring:
|
|||
max-wait: -1ms
|
||||
datasource:
|
||||
# mysql
|
||||
# url: jdbc:mysql://localhost:3306/nation_defence?allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
|
||||
# username: root
|
||||
# password: 123456
|
||||
# driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
url: jdbc:dm://192.168.0.52:5236
|
||||
username: NATION_DEFENCE
|
||||
password: Lidy1234
|
||||
driver-class-name: dm.jdbc.driver.DmDriver
|
||||
url: jdbc:mysql://localhost:3306/nation_defence?allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
|
||||
username: root
|
||||
password: 123456
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
# url: jdbc:dm://127.0.0.1:5236
|
||||
# username: SYSDBA
|
||||
# password: SYSDBA001
|
||||
# driver-class-name: dm.jdbc.driver.DmDriver
|
||||
hikari:
|
||||
minimum-idle: 5
|
||||
maximum-pool-size: 20
|
||||
|
|
@ -63,4 +63,13 @@ logging:
|
|||
level:
|
||||
com.baomidou.mybatisplus: warn
|
||||
org.apache.ibatis: warn
|
||||
third:
|
||||
auth:
|
||||
client_id: 233
|
||||
client_secret: 123
|
||||
token-url: http://32.15.80.150:99/oauth2Server/oauth2/token
|
||||
userinfo-url: http://32.15.80.150:99/oauth2Server/oauth2/userinfo
|
||||
jump_url: http://32.15.80.150:99/oauth2Server/oauth2/authorizeV2
|
||||
redirect_url: http://32.15.191.88:8888/redirect
|
||||
logout_url: ttp://32.15.80.150:99/oauth2Server/oauth2/logout
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@
|
|||
</div>
|
||||
</a>
|
||||
<div class="dropdown-menu dropdown-menu-end dropdown-menu-arrow">
|
||||
<a th:href="@{/logout}" class="dropdown-item">退出登录</a>
|
||||
<a th:href="@{/out}" class="dropdown-item">退出登录</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -56,10 +56,12 @@
|
|||
<div class="card card-md">
|
||||
<div class="card-body">
|
||||
<h2 class="h2 text-center mb-4" th:text="${systemTitle}"></h2>
|
||||
<form name="loginForm" id="loginForm" th:action="@{/toAuth}" method="get" autocomplete="off" novalidate>
|
||||
<form name="loginForm" id="loginForm" th:action="@{/toAuth}" method="get" autocomplete="off"
|
||||
novalidate>
|
||||
<div class="mb-3">
|
||||
|
||||
<input type="text" id="username" name="username" class="form-control " placeholder="用户名"
|
||||
<input type="text" id="username" name="username" class="form-control "
|
||||
placeholder="用户名"
|
||||
autocomplete="off">
|
||||
<div class="invalid-feedback" id="userName_error_tip"></div>
|
||||
</div>
|
||||
|
|
@ -73,8 +75,13 @@
|
|||
|
||||
<div class="form-footer">
|
||||
<button type="submit" class="btn btn-primary w-100">登录</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="form-footer">
|
||||
<button type="button" class="btn btn-success w-100" th:data-redirect-url="${jumpUrl}"
|
||||
onclick="jump(this)">统一认证登录
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
|
||||
|
|
@ -97,6 +104,12 @@
|
|||
|
||||
</html>
|
||||
<script>
|
||||
function jump(obj) {
|
||||
|
||||
;
|
||||
window.location = obj.dataset.redirectUrl;
|
||||
}
|
||||
|
||||
document.getElementById('loginForm').addEventListener("submit", function (e) {
|
||||
// 阻止默认表单提交
|
||||
e.preventDefault();
|
||||
|
|
@ -134,13 +147,12 @@
|
|||
if (data.code === 0) {
|
||||
// 例如:跳转到首页
|
||||
|
||||
window.location.href = "/home";
|
||||
window.location.href = "home";
|
||||
} else {
|
||||
if (data.code === -1) {//验证错误
|
||||
//遍历错误信息
|
||||
for (const item of data.errors) {
|
||||
|
||||
|
||||
document.getElementById(item.elementId).classList.add("is-invalid");
|
||||
document.getElementById(item.elementId + "_error_tip").innerHTML = item.message;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user