自己写一套权限控制,去掉spring security
This commit is contained in:
@@ -1,16 +1,14 @@
|
||||
package com.zyplayer.doc.core.json;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.serializer.SerializeConfig;
|
||||
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 文档返回数据格式
|
||||
*
|
||||
@@ -102,6 +100,17 @@ public class DocResponseJson<T> implements ResponseJson<T> {
|
||||
return new DocResponseJson<T>(500, errMsg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败
|
||||
*
|
||||
* @author 暮光:城中城
|
||||
* @since 2018年8月7日
|
||||
* @return
|
||||
*/
|
||||
public static <T> DocResponseJson<T> failure(int errCode, String errMsg) {
|
||||
return new DocResponseJson<T>(errCode, errMsg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功的返回方法
|
||||
*
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.zyplayer.doc.core.json;
|
||||
|
||||
public class HttpConst {
|
||||
|
||||
/** 每页显示条数 **/
|
||||
public static final int PAGE_NUMBER = 50;
|
||||
/** 默认当前页 **/
|
||||
public static final int CURRENT_PAGE = 1;
|
||||
|
||||
/** 图片验证码 **/
|
||||
public static final String SESSION_VERIFY_CODE = "SESSION_VERIFY_CODE";
|
||||
/** 邮箱验证码 **/
|
||||
public static final String SESSION_EMAIL_CODE = "SESSION_EMAIL_CODE";
|
||||
/** 请求失败的原因 **/
|
||||
public static final String SESSION_FAIL_REASON = "SESSION_FAIL_REASON";
|
||||
/** operator */
|
||||
public static final String OPERATOR = "OPERATOR";
|
||||
|
||||
/** 分页-总条数 */
|
||||
public static final String PAGE_TOTAL = "PAGE_TOTAL";
|
||||
/** 分页-当前页数 */
|
||||
public static final String PAGE_NOWPAGE = "PAGE_NOWPAGE";
|
||||
/** 分页-总页数 */
|
||||
public static final String PAGE_PAGECOUNT = "PAGE_PAGECOUNT";
|
||||
/** 分页-每页多少条 */
|
||||
public static final String PAGE_SIZE = "PAGE_SIZE";
|
||||
|
||||
/** 会话连接 */
|
||||
public static final String ACCESS_TOKEN = "accessToken";
|
||||
/** 存在于ThreadLocal的http request */
|
||||
public static final String HTTP_SERVLET_REQUEST = "HTTP_SERVLET_REQUEST";
|
||||
/** 存在于ThreadLocal的HTTP_SESSION */
|
||||
public static final String HTTP_SESSION = "HTTP_SESSION";
|
||||
|
||||
/** 存于operator中权限的缓存头 **/
|
||||
public static final String AUTH_CACHE_HEAD = "AUTH_CACHE_HEAD_";
|
||||
/** 存于operator中的用户信息 **/
|
||||
public static final String CACHE_OPERATOR_USER_INFO = "USER_INFO";
|
||||
/** 存于operator中的城市信息 **/
|
||||
public static final String CACHE_OPERATOR_CITY_ID = "CITY_ID";
|
||||
/** 存于operator中的token绑定的访问信息,使得换一台电脑不能使用此token **/
|
||||
public static final String CACHE_OPERATOR_ACCESS_TOKEN_VALIDATE = "ACCESS_TOKEN_VALIDATE";
|
||||
/** 存于operator中的token信息 **/
|
||||
public static final String CACHE_OPERATOR_ACCESS_TOKEN = "accessToken";
|
||||
/** 存于operator中的微信sessionKey信息 **/
|
||||
public static final String CACHE_OPERATOR_SESSION_KEY = "sessionKey";
|
||||
|
||||
// 新版本使用的错误码
|
||||
/** 成功 **/
|
||||
public static final int SUCCESS = 200;
|
||||
/** 提示性状态 需要客户端配合展示 **/
|
||||
public static final int CONFIRM_CODE = 300;
|
||||
/** accessToken非法或过期,需要重新登录 **/
|
||||
public static final int TOKEN_TIMEOUT = 400;
|
||||
/** 业务接口缺少参数,errMsg会返回错误信息 **/
|
||||
public static final int MISSING_PARAMETER = 401;
|
||||
/** API 未授权 **/
|
||||
public static final int UNAUTHORIZED = 402;
|
||||
/** 接口调用频率超限 **/
|
||||
public static final int CALL_FREQUENCY_GAUGE = 403;
|
||||
/** 微信未扫码登录异常 **/
|
||||
public static final int WX_NOT_LOGIN = 404;
|
||||
/** 请升级至新版使用此功能 **/
|
||||
public static final int NEED_UPGRADE = 405;
|
||||
/** 服务器端未知错误 **/
|
||||
public static final int OTHER_FAIL = 500;
|
||||
}
|
||||
@@ -88,9 +88,18 @@
|
||||
<artifactId>freemarker</artifactId>
|
||||
</dependency>
|
||||
<!-- 整合spring security -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springframework.boot</groupId>-->
|
||||
<!-- <artifactId>spring-boot-starter-security</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- aspectj -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjtools</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.zyplayer.doc.data.aspect;
|
||||
|
||||
import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
import com.zyplayer.doc.core.json.HttpConst;
|
||||
import com.zyplayer.doc.core.json.ResponseJson;
|
||||
import com.zyplayer.doc.data.config.security.DocUserDetails;
|
||||
import com.zyplayer.doc.data.config.security.DocUserUtil;
|
||||
import com.zyplayer.doc.data.service.manage.UserAuthService;
|
||||
import com.zyplayer.doc.data.utils.BeanUtil;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
public class AuthAspect {
|
||||
|
||||
@Resource
|
||||
private UserAuthService userAuthService;
|
||||
|
||||
@Around(value = "@annotation(AuthMan) || @within(AuthMan)")
|
||||
public Object authController(ProceedingJoinPoint pjp) throws Throwable {
|
||||
AuthMan authMan = BeanUtil.getAnnotation(pjp, AuthMan.class);
|
||||
ResponseBody responseBody = BeanUtil.getAnnotation(pjp, ResponseBody.class);
|
||||
RestController restController = BeanUtil.getAnnotation(pjp, RestController.class);
|
||||
boolean isResponseBody = (restController != null || responseBody != null);
|
||||
|
||||
DocUserDetails currentUser = DocUserUtil.getCurrentUser();
|
||||
if (currentUser == null) {
|
||||
String reason = "你访问的内容需要登录,请登录后再试";
|
||||
if (isResponseBody) {
|
||||
return DocResponseJson.failure(HttpConst.TOKEN_TIMEOUT, reason);
|
||||
} else {
|
||||
return authMan.authUrl();
|
||||
}
|
||||
}
|
||||
// 判断权限是否足够
|
||||
boolean haveAuth = DocUserUtil.haveAuth(authMan.value());
|
||||
if (haveAuth) {
|
||||
return pjp.proceed();
|
||||
}
|
||||
String reasonStr = "没有操作权限,请联系管理员";
|
||||
if (isResponseBody) {
|
||||
Method method = ((MethodSignature) pjp.getSignature()).getMethod();
|
||||
if (method.getReturnType().equals(ResponseJson.class)) {
|
||||
return DocResponseJson.warn(reasonStr);
|
||||
} else {
|
||||
try {
|
||||
return Class.forName(method.getReturnType().getName()).newInstance();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return authMan.authUrl();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.zyplayer.doc.data.aspect;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Target({ElementType.METHOD,ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface AuthMan {
|
||||
String[] value() default {};
|
||||
String authUrl() default "common/authfailed";
|
||||
boolean all() default false;
|
||||
}
|
||||
@@ -1,18 +1,53 @@
|
||||
package com.zyplayer.doc.data.config.security;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public class DocUserDetails implements UserDetails {
|
||||
private static final long serialVersionUID = 1L;
|
||||
import java.util.Set;
|
||||
|
||||
public class DocUserDetails {
|
||||
private Long userId;
|
||||
private String username;
|
||||
private String password;
|
||||
private boolean enabled;
|
||||
private Collection<? extends GrantedAuthority> authorities;
|
||||
private Set<String> authorities;
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public Set<String> getAuthorities() {
|
||||
return authorities;
|
||||
}
|
||||
|
||||
public void setAuthorities(Set<String> authorities) {
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
public DocUserDetails(Long userId, String username, String password, boolean enabled) {
|
||||
super();
|
||||
@@ -22,8 +57,7 @@ public class DocUserDetails implements UserDetails {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public DocUserDetails(Long userId, String username, String password, boolean enabled,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
public DocUserDetails(Long userId, String username, String password, boolean enabled, Set<String> authorities) {
|
||||
super();
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
@@ -32,48 +66,14 @@ public class DocUserDetails implements UserDetails {
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return authorities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MyUserDetails [userId=" + userId + ", username=" + username + ", password=" + password + ", enabled="
|
||||
+ enabled + ", authorities=" + authorities + "]";
|
||||
return "DocUserDetails{" +
|
||||
"userId=" + userId +
|
||||
", username='" + username + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
", enabled=" + enabled +
|
||||
", authorities=" + authorities +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,82 @@
|
||||
package com.zyplayer.doc.data.config.security;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import com.zyplayer.doc.data.utils.CacheUtil;
|
||||
|
||||
/**
|
||||
* 用户工具类
|
||||
* @author 暮光:城中城
|
||||
* @since 2019年05月25日
|
||||
*/
|
||||
public class DocUserUtil {
|
||||
private static ThreadLocal<DocUserDetails> DOC_USER_DETAILS = new ThreadLocal<>();
|
||||
private static ThreadLocal<String> ACCESS_TOKEN = new ThreadLocal<>();
|
||||
|
||||
//
|
||||
// /**
|
||||
// * 获取当前用户
|
||||
// * @return 用户信息
|
||||
// */
|
||||
// public static DocUserDetails getCurrentUser() {
|
||||
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
// if (authentication != null) {
|
||||
// Object principal = authentication.getPrincipal();
|
||||
// if (principal instanceof DocUserDetails) {
|
||||
// return (DocUserDetails) principal;
|
||||
// }
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
|
||||
public static void setAccessToken(String accessToken) {
|
||||
DocUserUtil.ACCESS_TOKEN.set(accessToken);
|
||||
}
|
||||
|
||||
public static boolean haveAuth(String... authNames) {
|
||||
DocUserDetails currentUser = getCurrentUser();
|
||||
if (currentUser == null) {
|
||||
return false;
|
||||
}
|
||||
for (String authName : authNames) {
|
||||
if (!currentUser.getAuthorities().contains(authName)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户
|
||||
*
|
||||
* @return 用户信息
|
||||
*/
|
||||
public static DocUserDetails getCurrentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object principal = authentication.getPrincipal();
|
||||
if (principal instanceof DocUserDetails) {
|
||||
return (DocUserDetails) principal;
|
||||
DocUserDetails docUser = DOC_USER_DETAILS.get();
|
||||
if (docUser == null) {
|
||||
docUser = CacheUtil.get(ACCESS_TOKEN.get());
|
||||
if (docUser != null) {
|
||||
DOC_USER_DETAILS.set(docUser);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return docUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前用户
|
||||
*/
|
||||
public static void setCurrentUser(String accessToken, DocUserDetails docUser) {
|
||||
DOC_USER_DETAILS.set(docUser);
|
||||
CacheUtil.put(accessToken, docUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
*/
|
||||
public static void logout() {
|
||||
CacheUtil.remove(ACCESS_TOKEN.get());
|
||||
}
|
||||
|
||||
public static void clean() {
|
||||
DocUserUtil.DOC_USER_DETAILS.remove();
|
||||
DocUserUtil.ACCESS_TOKEN.remove();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.zyplayer.doc.data.utils;
|
||||
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.Signature;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class BeanUtil {
|
||||
|
||||
@SuppressWarnings({"unchecked"})
|
||||
public static <T extends Annotation> T getAnnotation(JoinPoint pjp, Class<T> t) throws Exception {
|
||||
Method method = ((MethodSignature) pjp.getSignature()).getMethod();
|
||||
T annotation = method.getAnnotation(t);// 方法上定义的
|
||||
if (annotation == null) {
|
||||
annotation = (T) pjp.getSignature().getDeclaringType().getAnnotation(t);// 类上定义的
|
||||
if (annotation == null) {
|
||||
Object target = pjp.getTarget();
|
||||
annotation = target.getClass().getAnnotation(t);// 实现类上定义的
|
||||
if (annotation == null) {
|
||||
Signature sig = pjp.getSignature();
|
||||
if (sig instanceof MethodSignature) {
|
||||
MethodSignature msig = (MethodSignature) sig;
|
||||
Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
|
||||
annotation = currentMethod.getAnnotation(t);// 实现类的方法上定义的
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return annotation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.zyplayer.doc.data.utils;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 缓存工具类
|
||||
* @author 暮光:城中城
|
||||
* @since 2019年05月25日
|
||||
*/
|
||||
public class CacheUtil {
|
||||
|
||||
// 定期清除过期的key
|
||||
static {
|
||||
Timer timer = new Timer();
|
||||
timer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
long currentTimeMillis = System.currentTimeMillis();
|
||||
for (Map.Entry<String, CacheTime> entry : cacheTimeMap.entrySet()) {
|
||||
CacheTime cacheTime = entry.getValue();
|
||||
if (currentTimeMillis - cacheTime.getLastVisitTime() < (cacheTime.getSecond() * 1000)) {
|
||||
continue;
|
||||
}
|
||||
cacheMap.remove(entry.getKey());
|
||||
}
|
||||
}
|
||||
}, 0, 1000);
|
||||
}
|
||||
|
||||
private static Map<String, Object> cacheMap = new ConcurrentHashMap<>();
|
||||
private static Map<String, CacheTime> cacheTimeMap = new ConcurrentHashMap<>();
|
||||
|
||||
public static void put(String key, Object value) {
|
||||
put(key, value, (long) (60 * 60 * 12));
|
||||
}
|
||||
|
||||
public static void put(String key, Object value, Long second) {
|
||||
cacheMap.put(key, value);
|
||||
cacheTimeMap.put(key, new CacheTime(second));
|
||||
}
|
||||
|
||||
public static void remove(String key) {
|
||||
cacheMap.remove(key);
|
||||
cacheTimeMap.remove(key);
|
||||
}
|
||||
|
||||
public static <T> T get(String key) {
|
||||
CacheTime cacheTime = cacheTimeMap.get(key);
|
||||
if (cacheTime != null) {
|
||||
cacheTime.setLastVisitTime(System.currentTimeMillis());
|
||||
cacheTimeMap.put(key, cacheTime);
|
||||
}
|
||||
return (T) cacheMap.get(key);
|
||||
}
|
||||
|
||||
private static class CacheTime {
|
||||
private Long second;
|
||||
private Long lastVisitTime;
|
||||
|
||||
public CacheTime(Long second) {
|
||||
this.second = second;
|
||||
this.lastVisitTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public Long getSecond() {
|
||||
return second;
|
||||
}
|
||||
|
||||
public void setSecond(Long second) {
|
||||
this.second = second;
|
||||
}
|
||||
|
||||
public Long getLastVisitTime() {
|
||||
return lastVisitTime;
|
||||
}
|
||||
|
||||
public void setLastVisitTime(Long lastVisitTime) {
|
||||
this.lastVisitTime = lastVisitTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,10 +144,10 @@
|
||||
<artifactId>freemarker</artifactId>
|
||||
</dependency>
|
||||
<!-- 整合spring security -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springframework.boot</groupId>-->
|
||||
<!-- <artifactId>spring-boot-starter-security</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//package com.zyplayer.doc.manage.framework.config.security;
|
||||
//
|
||||
//import com.alibaba.fastjson.JSONObject;
|
||||
//import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//import org.springframework.security.core.Authentication;
|
||||
//import org.springframework.security.core.context.SecurityContext;
|
||||
//import org.springframework.security.core.context.SecurityContextHolder;
|
||||
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
//import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
//import org.springframework.stereotype.Component;
|
||||
//
|
||||
//import javax.servlet.ServletException;
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
//import java.io.IOException;
|
||||
//import java.io.PrintWriter;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//
|
||||
//@Component
|
||||
//public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
|
||||
// private static Logger logger = LoggerFactory.getLogger(CustomizeAuthenticationSuccessHandler.class);
|
||||
//
|
||||
// @Override
|
||||
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
|
||||
//
|
||||
// logger.info("AT onAuthenticationSuccess(...) function!");
|
||||
//
|
||||
// WebAuthenticationDetails details = (WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
|
||||
// logger.info("login--IP:" + details.getRemoteAddress());
|
||||
//
|
||||
// SecurityContext context = SecurityContextHolder.getContext();
|
||||
// Authentication authentication1 = context.getAuthentication();
|
||||
// Object principal = authentication1.getPrincipal();
|
||||
// Object principal1 = authentication.getPrincipal();
|
||||
//
|
||||
// String name = authentication.getName();
|
||||
// logger.info("login--name:" + name + " principal:" + principal + " principal1:" + principal1);
|
||||
//
|
||||
// PrintWriter out = null;
|
||||
// try {
|
||||
// out = response.getWriter();
|
||||
// Map<String, Object> map = new HashMap<>();
|
||||
// map.put("user", principal);
|
||||
// map.put("name", name);
|
||||
// out.append(JSONObject.toJSONString(DocResponseJson.ok(map)));
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// } finally {
|
||||
// if (out != null) {
|
||||
// out.close();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -1,46 +1,46 @@
|
||||
package com.zyplayer.doc.manage.framework.config.security;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.DefaultRedirectStrategy;
|
||||
import org.springframework.security.web.RedirectStrategy;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.savedrequest.SavedRequest;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
|
||||
public class DocAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(DocAuthenticationSuccessHandler.class);
|
||||
|
||||
private RequestCache requestCache = new HttpSessionRequestCache();
|
||||
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
|
||||
|
||||
@Override
|
||||
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
|
||||
SavedRequest savedRequest = requestCache.getRequest(request, response);
|
||||
String targetUrl = savedRequest.getRedirectUrl();
|
||||
boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
|
||||
if (isAjax) {
|
||||
Map<String, Object> result = new HashMap<String, Object>();
|
||||
result.put("url", targetUrl);
|
||||
response.getWriter().print(JSON.toJSONString(result));
|
||||
response.getWriter().flush();
|
||||
} else {
|
||||
redirectStrategy.sendRedirect(request, response, targetUrl);
|
||||
}
|
||||
logger.info("Redirecting to DefaultSavedRequest Url: " + targetUrl);
|
||||
}
|
||||
|
||||
}
|
||||
//package com.zyplayer.doc.manage.framework.config.security;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//
|
||||
//import javax.servlet.ServletException;
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
//
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//import org.springframework.security.core.Authentication;
|
||||
//import org.springframework.security.web.DefaultRedirectStrategy;
|
||||
//import org.springframework.security.web.RedirectStrategy;
|
||||
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
//import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
//import org.springframework.security.web.savedrequest.RequestCache;
|
||||
//import org.springframework.security.web.savedrequest.SavedRequest;
|
||||
//
|
||||
//import com.alibaba.fastjson.JSON;
|
||||
//
|
||||
//public class DocAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
|
||||
//
|
||||
// private static Logger logger = LoggerFactory.getLogger(DocAuthenticationSuccessHandler.class);
|
||||
//
|
||||
// private RequestCache requestCache = new HttpSessionRequestCache();
|
||||
// private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
|
||||
//
|
||||
// @Override
|
||||
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
|
||||
// SavedRequest savedRequest = requestCache.getRequest(request, response);
|
||||
// String targetUrl = savedRequest.getRedirectUrl();
|
||||
// boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
|
||||
// if (isAjax) {
|
||||
// Map<String, Object> result = new HashMap<String, Object>();
|
||||
// result.put("url", targetUrl);
|
||||
// response.getWriter().print(JSON.toJSONString(result));
|
||||
// response.getWriter().flush();
|
||||
// } else {
|
||||
// redirectStrategy.sendRedirect(request, response, targetUrl);
|
||||
// }
|
||||
// logger.info("Redirecting to DefaultSavedRequest Url: " + targetUrl);
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -1,58 +1,58 @@
|
||||
package com.zyplayer.doc.manage.framework.config.security;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.zyplayer.doc.data.config.security.DocUserDetails;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.AuthInfo;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.UserAuth;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.UserInfo;
|
||||
import com.zyplayer.doc.data.service.manage.AuthInfoService;
|
||||
import com.zyplayer.doc.data.service.manage.UserAuthService;
|
||||
import com.zyplayer.doc.data.service.manage.UserInfoService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class DocDetailsServiceImpl implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
private UserInfoService userInfoService;
|
||||
@Autowired
|
||||
private UserAuthService userAuthService;
|
||||
@Autowired
|
||||
private AuthInfoService authInfoService;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String userNo) throws UsernameNotFoundException {
|
||||
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("user_no", userNo);
|
||||
UserInfo userInfo = userInfoService.getOne(queryWrapper);
|
||||
if (userInfo == null) {
|
||||
throw new UsernameNotFoundException("用户名'" + userNo + "'没有找到!");
|
||||
}
|
||||
QueryWrapper<UserAuth> authWrapper = new QueryWrapper<>();
|
||||
authWrapper.eq("user_id", userInfo.getId()).eq("del_flag", "0");
|
||||
List<UserAuth> userAuthList = userAuthService.list(authWrapper);
|
||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
if (userAuthList != null && userAuthList.size() > 0) {
|
||||
List<Long> authIdList = userAuthList.stream().map(UserAuth::getAuthId).collect(Collectors.toList());
|
||||
Collection<AuthInfo> authInfoList = authInfoService.listByIds(authIdList);
|
||||
authInfoList.forEach(val -> {
|
||||
authorities.add(new SimpleGrantedAuthority(val.getAuthName()));
|
||||
});
|
||||
}
|
||||
//String pwdMd5 = DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes());
|
||||
DocUserDetails userDetails = new DocUserDetails(userInfo.getId(), userInfo.getUserName(), userInfo.getPassword(), true, authorities);
|
||||
return userDetails;
|
||||
}
|
||||
|
||||
}
|
||||
//package com.zyplayer.doc.manage.framework.config.security;
|
||||
//
|
||||
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
//import com.zyplayer.doc.data.config.security.DocUserDetails;
|
||||
//import com.zyplayer.doc.data.repository.manage.entity.AuthInfo;
|
||||
//import com.zyplayer.doc.data.repository.manage.entity.UserAuth;
|
||||
//import com.zyplayer.doc.data.repository.manage.entity.UserInfo;
|
||||
//import com.zyplayer.doc.data.service.manage.AuthInfoService;
|
||||
//import com.zyplayer.doc.data.service.manage.UserAuthService;
|
||||
//import com.zyplayer.doc.data.service.manage.UserInfoService;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.security.core.GrantedAuthority;
|
||||
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
//import org.springframework.security.core.userdetails.UserDetails;
|
||||
//import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
//import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
//import org.springframework.stereotype.Service;
|
||||
//
|
||||
//import java.util.ArrayList;
|
||||
//import java.util.Collection;
|
||||
//import java.util.List;
|
||||
//import java.util.stream.Collectors;
|
||||
//
|
||||
//@Service
|
||||
//public class DocDetailsServiceImpl implements UserDetailsService {
|
||||
//
|
||||
// @Autowired
|
||||
// private UserInfoService userInfoService;
|
||||
// @Autowired
|
||||
// private UserAuthService userAuthService;
|
||||
// @Autowired
|
||||
// private AuthInfoService authInfoService;
|
||||
//
|
||||
// @Override
|
||||
// public UserDetails loadUserByUsername(String userNo) throws UsernameNotFoundException {
|
||||
// QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
|
||||
// queryWrapper.eq("user_no", userNo);
|
||||
// UserInfo userInfo = userInfoService.getOne(queryWrapper);
|
||||
// if (userInfo == null) {
|
||||
// throw new UsernameNotFoundException("用户名'" + userNo + "'没有找到!");
|
||||
// }
|
||||
// QueryWrapper<UserAuth> authWrapper = new QueryWrapper<>();
|
||||
// authWrapper.eq("user_id", userInfo.getId()).eq("del_flag", "0");
|
||||
// List<UserAuth> userAuthList = userAuthService.list(authWrapper);
|
||||
// List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
// if (userAuthList != null && userAuthList.size() > 0) {
|
||||
// List<Long> authIdList = userAuthList.stream().map(UserAuth::getAuthId).collect(Collectors.toList());
|
||||
// Collection<AuthInfo> authInfoList = authInfoService.listByIds(authIdList);
|
||||
// authInfoList.forEach(val -> {
|
||||
// authorities.add(new SimpleGrantedAuthority(val.getAuthName()));
|
||||
// });
|
||||
// }
|
||||
// //String pwdMd5 = DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes());
|
||||
// DocUserDetails userDetails = new DocUserDetails(userInfo.getId(), userInfo.getUserName(), userInfo.getPassword(), true, authorities);
|
||||
// return userDetails;
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
||||
@@ -1,53 +1,53 @@
|
||||
package com.zyplayer.doc.manage.framework.config.security;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class DocUserFilter implements Filter{
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
Cookie[] cookies = httpRequest.getCookies();
|
||||
boolean haveCtx = false;
|
||||
Object ctxObj = httpRequest.getServletContext().getAttribute("ctx");
|
||||
String ctxStr = String.valueOf(ctxObj);
|
||||
if (cookies != null && cookies.length > 0) {
|
||||
for (Cookie cookie : cookies) {
|
||||
if ("ctx".equals(cookie.getName()) && ctxStr.equals(cookie.getValue())) {
|
||||
haveCtx = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!haveCtx) {
|
||||
// 前后端分离的,前段拿不到项目名,直接写/是不对的,只有后端放到cookie里给前端
|
||||
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
Cookie cookieAdd = new Cookie("ctx", ctxStr);
|
||||
cookieAdd.setPath("/");
|
||||
httpResponse.addCookie(cookieAdd);
|
||||
}
|
||||
chain.doFilter(httpRequest, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
}
|
||||
//package com.zyplayer.doc.manage.framework.config.security;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//
|
||||
//import javax.servlet.Filter;
|
||||
//import javax.servlet.FilterChain;
|
||||
//import javax.servlet.FilterConfig;
|
||||
//import javax.servlet.ServletException;
|
||||
//import javax.servlet.ServletRequest;
|
||||
//import javax.servlet.ServletResponse;
|
||||
//import javax.servlet.http.Cookie;
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
//
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//
|
||||
//@Configuration
|
||||
//public class DocUserFilter implements Filter{
|
||||
//
|
||||
// @Override
|
||||
// public void init(FilterConfig filterConfig) throws ServletException {
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
// HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
// Cookie[] cookies = httpRequest.getCookies();
|
||||
// boolean haveCtx = false;
|
||||
// Object ctxObj = httpRequest.getServletContext().getAttribute("ctx");
|
||||
// String ctxStr = String.valueOf(ctxObj);
|
||||
// if (cookies != null && cookies.length > 0) {
|
||||
// for (Cookie cookie : cookies) {
|
||||
// if ("ctx".equals(cookie.getName()) && ctxStr.equals(cookie.getValue())) {
|
||||
// haveCtx = true;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// if (!haveCtx) {
|
||||
// // 前后端分离的,前段拿不到项目名,直接写/是不对的,只有后端放到cookie里给前端
|
||||
// HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
// Cookie cookieAdd = new Cookie("ctx", ctxStr);
|
||||
// cookieAdd.setPath("/");
|
||||
// httpResponse.addCookie(cookieAdd);
|
||||
// }
|
||||
// chain.doFilter(httpRequest, response);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void destroy() {
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
||||
@@ -1,47 +1,47 @@
|
||||
package com.zyplayer.doc.manage.framework.config.security;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
public class DocUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
|
||||
// 是否开启验证码功能
|
||||
private boolean isOpenValidateCode = false;
|
||||
|
||||
public static final String VALIDATE_CODE = "validateCode";
|
||||
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
|
||||
if (isOpenValidateCode) {
|
||||
checkValidateCode(request);
|
||||
}
|
||||
return super.attemptAuthentication(request, response);
|
||||
}
|
||||
|
||||
protected void checkValidateCode(HttpServletRequest request) {
|
||||
HttpSession session = request.getSession();
|
||||
String sessionCode = this.obtainSessionValidateCode(session);
|
||||
// 让上一次的验证码失效
|
||||
session.setAttribute(VALIDATE_CODE, null);
|
||||
String parameterCode = this.obtainValidateCodeParameter(request);
|
||||
if (StringUtils.isEmpty(sessionCode) || !sessionCode.equalsIgnoreCase(parameterCode)) {
|
||||
throw new AuthenticationServiceException("验证码错误!");
|
||||
}
|
||||
}
|
||||
|
||||
private String obtainValidateCodeParameter(HttpServletRequest request) {
|
||||
Object obj = request.getParameter(VALIDATE_CODE);
|
||||
return null == obj ? "" : obj.toString();
|
||||
}
|
||||
|
||||
protected String obtainSessionValidateCode(HttpSession session) {
|
||||
Object obj = session.getAttribute(VALIDATE_CODE);
|
||||
return null == obj ? "" : obj.toString();
|
||||
}
|
||||
|
||||
}
|
||||
//package com.zyplayer.doc.manage.framework.config.security;
|
||||
//
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
//import javax.servlet.http.HttpSession;
|
||||
//
|
||||
//import org.apache.commons.lang.StringUtils;
|
||||
//import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
//import org.springframework.security.core.Authentication;
|
||||
//import org.springframework.security.core.AuthenticationException;
|
||||
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
//
|
||||
//public class DocUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
|
||||
// // 是否开启验证码功能
|
||||
// private boolean isOpenValidateCode = false;
|
||||
//
|
||||
// public static final String VALIDATE_CODE = "validateCode";
|
||||
//
|
||||
// public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
|
||||
// if (isOpenValidateCode) {
|
||||
// checkValidateCode(request);
|
||||
// }
|
||||
// return super.attemptAuthentication(request, response);
|
||||
// }
|
||||
//
|
||||
// protected void checkValidateCode(HttpServletRequest request) {
|
||||
// HttpSession session = request.getSession();
|
||||
// String sessionCode = this.obtainSessionValidateCode(session);
|
||||
// // 让上一次的验证码失效
|
||||
// session.setAttribute(VALIDATE_CODE, null);
|
||||
// String parameterCode = this.obtainValidateCodeParameter(request);
|
||||
// if (StringUtils.isEmpty(sessionCode) || !sessionCode.equalsIgnoreCase(parameterCode)) {
|
||||
// throw new AuthenticationServiceException("验证码错误!");
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private String obtainValidateCodeParameter(HttpServletRequest request) {
|
||||
// Object obj = request.getParameter(VALIDATE_CODE);
|
||||
// return null == obj ? "" : obj.toString();
|
||||
// }
|
||||
//
|
||||
// protected String obtainSessionValidateCode(HttpSession session) {
|
||||
// Object obj = session.getAttribute(VALIDATE_CODE);
|
||||
// return null == obj ? "" : obj.toString();
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -1,156 +1,156 @@
|
||||
package com.zyplayer.doc.manage.framework.config.security;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.RememberMeAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.authentication.*;
|
||||
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter;
|
||||
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
|
||||
import org.springframework.util.DigestUtils;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Value("${zyplayer.doc.manage.login-page}")
|
||||
private String loginPage;
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
|
||||
/**
|
||||
* 忽略静态文件
|
||||
*/
|
||||
@Override
|
||||
public void configure(WebSecurity web) throws Exception {
|
||||
web.ignoring().antMatchers();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// 无需登录即可访问的接口
|
||||
String[] permitAllAntPatterns = {
|
||||
// 登录接口
|
||||
"/login/**", "/static/manage/login.html",
|
||||
// 开放接口的静态文件和接口
|
||||
"/open-doc.html", "/webjars/open-doc/**", "/swagger-mg-ui/open-doc/**",
|
||||
"/open-wiki.html", "/webjars/doc-wiki/**", "/zyplayer-doc-wiki/open-api/**",
|
||||
// 文件访问接口,开放文档需要能使用,在接口里面做权限判断
|
||||
"/zyplayer-doc-wiki/common/file",
|
||||
// http代理请求接口,有白名单限制,也不怕随便请求到内网资源了
|
||||
"/swagger-mg-ui/http/**",
|
||||
// 静态资源
|
||||
"/webjars/zui/**", "/webjars/vue/**", "/static/lib/**"
|
||||
};
|
||||
// 文档页面需要具有文档权限
|
||||
String[] docAntPatterns = {
|
||||
"/document.html", "/doc-db.html", "/doc.html", "/swagger-ui.html", "/doc-dubbo.html",
|
||||
"/doc-wiki.html",
|
||||
"/swagger-mg-ui/document/**", "/swagger-mg-ui/storage/**", "/swagger-resources/**"
|
||||
};
|
||||
http.authorizeRequests()
|
||||
.antMatchers(permitAllAntPatterns).permitAll()
|
||||
.antMatchers(docAntPatterns).hasAuthority("DOC_ALL")
|
||||
// 其他地址的访问均需登录
|
||||
.anyRequest().authenticated().and()
|
||||
// 添加验证码验证
|
||||
.addFilterAt(myUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
|
||||
.exceptionHandling()
|
||||
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint(loginPage))
|
||||
.and().addFilterAt(rememberMeAuthenticationFilter(), RememberMeAuthenticationFilter.class)
|
||||
// 指定登录页面的请求路径
|
||||
.formLogin().loginPage(loginPage)
|
||||
// 登陆处理路径
|
||||
.loginProcessingUrl("/login").permitAll()
|
||||
// 退出请求的默认路径为logout
|
||||
.and().logout().deleteCookies("remember-me")
|
||||
.logoutUrl("/logout").logoutSuccessUrl(loginPage)
|
||||
.permitAll()
|
||||
// 开启rememberMe,设置一个私钥专供testall项目使用,注意与下面TokenBasedRememberMeServices的key保持一致
|
||||
// .rememberMe().key("testallKey").and()
|
||||
// 关闭csrf
|
||||
.and().csrf().disable()
|
||||
// X-Frame-Options: SAMEORIGIN 表示该页面可以在相同域名页面的 frame 中展示
|
||||
.headers().frameOptions().sameOrigin();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userDetailsServiceImpl())
|
||||
.passwordEncoder(new PasswordEncoder() {
|
||||
@Override
|
||||
public String encode(CharSequence charSequence) {
|
||||
return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
|
||||
}
|
||||
@Override
|
||||
public boolean matches(CharSequence charSequence, String s) {
|
||||
String digestAsHex = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
|
||||
return Objects.equals(s, digestAsHex);
|
||||
}
|
||||
}).and().authenticationProvider(rememberMeAuthenticationProvider());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DocDetailsServiceImpl userDetailsServiceImpl() {
|
||||
return new DocDetailsServiceImpl();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DocUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter() throws Exception {
|
||||
DocUsernamePasswordAuthenticationFilter myFilter = new DocUsernamePasswordAuthenticationFilter();
|
||||
myFilter.setAuthenticationManager(authenticationManagerBean());
|
||||
myFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
|
||||
myFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
|
||||
myFilter.setRememberMeServices(tokenBasedRememberMeServices());
|
||||
return myFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationSuccessHandler authenticationSuccessHandler() {
|
||||
return new SimpleUrlAuthenticationSuccessHandler("/login/success");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationFailureHandler authenticationFailureHandler() {
|
||||
return new SimpleUrlAuthenticationFailureHandler("/login/failure");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TokenBasedRememberMeServices tokenBasedRememberMeServices() {
|
||||
TokenBasedRememberMeServices tbrms = new TokenBasedRememberMeServices("testallKey", userDetailsServiceImpl());
|
||||
// 设置cookie过期时间为2天
|
||||
tbrms.setTokenValiditySeconds(60 * 60 * 24 * 2);
|
||||
// 设置checkbox的参数名为rememberMe(默认为remember-me),注意如果是ajax请求,参数名不是checkbox的name而是在ajax的data里
|
||||
tbrms.setParameter("rememberMe");
|
||||
tbrms.setAlwaysRemember(false);
|
||||
return tbrms;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RememberMeAuthenticationProvider rememberMeAuthenticationProvider() {
|
||||
RememberMeAuthenticationProvider rmap = new RememberMeAuthenticationProvider("testallKey");
|
||||
return rmap;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RememberMeAuthenticationFilter rememberMeAuthenticationFilter() throws Exception {
|
||||
RememberMeAuthenticationFilter myFilter = new RememberMeAuthenticationFilter(authenticationManagerBean(), tokenBasedRememberMeServices());
|
||||
return myFilter;
|
||||
}
|
||||
|
||||
}
|
||||
//package com.zyplayer.doc.manage.framework.config.security;
|
||||
//
|
||||
//import org.springframework.beans.factory.annotation.Value;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//import org.springframework.security.authentication.AuthenticationManager;
|
||||
//import org.springframework.security.authentication.RememberMeAuthenticationProvider;
|
||||
//import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
//import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
//import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
//import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
//import org.springframework.security.web.authentication.*;
|
||||
//import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter;
|
||||
//import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
|
||||
//import org.springframework.util.DigestUtils;
|
||||
//
|
||||
//import java.util.Objects;
|
||||
//
|
||||
//@Configuration
|
||||
//@EnableWebSecurity
|
||||
//@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
//public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
//
|
||||
// @Value("${zyplayer.doc.manage.login-page}")
|
||||
// private String loginPage;
|
||||
//
|
||||
// @Bean
|
||||
// @Override
|
||||
// public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
// return super.authenticationManagerBean();
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 忽略静态文件
|
||||
// */
|
||||
// @Override
|
||||
// public void configure(WebSecurity web) throws Exception {
|
||||
// web.ignoring().antMatchers();
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// protected void configure(HttpSecurity http) throws Exception {
|
||||
// // 无需登录即可访问的接口
|
||||
// String[] permitAllAntPatterns = {
|
||||
// // 登录接口
|
||||
// "/login/**", "/static/manage/login.html",
|
||||
// // 开放接口的静态文件和接口
|
||||
// "/open-doc.html", "/webjars/open-doc/**", "/swagger-mg-ui/open-doc/**",
|
||||
// "/open-wiki.html", "/webjars/doc-wiki/**", "/zyplayer-doc-wiki/open-api/**",
|
||||
// // 文件访问接口,开放文档需要能使用,在接口里面做权限判断
|
||||
// "/zyplayer-doc-wiki/common/file",
|
||||
// // http代理请求接口,有白名单限制,也不怕随便请求到内网资源了
|
||||
// "/swagger-mg-ui/http/**",
|
||||
// // 静态资源
|
||||
// "/webjars/zui/**", "/webjars/vue/**", "/static/lib/**"
|
||||
// };
|
||||
// // 文档页面需要具有文档权限
|
||||
// String[] docAntPatterns = {
|
||||
// "/document.html", "/doc-db.html", "/doc.html", "/swagger-ui.html", "/doc-dubbo.html",
|
||||
// "/doc-wiki.html",
|
||||
// "/swagger-mg-ui/document/**", "/swagger-mg-ui/storage/**", "/swagger-resources/**"
|
||||
// };
|
||||
// http.authorizeRequests()
|
||||
// .antMatchers(permitAllAntPatterns).permitAll()
|
||||
// .antMatchers(docAntPatterns).hasAuthority("DOC_ALL")
|
||||
// // 其他地址的访问均需登录
|
||||
// .anyRequest().authenticated().and()
|
||||
// // 添加验证码验证
|
||||
// .addFilterAt(myUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
|
||||
// .exceptionHandling()
|
||||
// .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint(loginPage))
|
||||
// .and().addFilterAt(rememberMeAuthenticationFilter(), RememberMeAuthenticationFilter.class)
|
||||
// // 指定登录页面的请求路径
|
||||
// .formLogin().loginPage(loginPage)
|
||||
// // 登陆处理路径
|
||||
// .loginProcessingUrl("/login").permitAll()
|
||||
// // 退出请求的默认路径为logout
|
||||
// .and().logout().deleteCookies("remember-me")
|
||||
// .logoutUrl("/logout").logoutSuccessUrl(loginPage)
|
||||
// .permitAll()
|
||||
// // 开启rememberMe,设置一个私钥专供testall项目使用,注意与下面TokenBasedRememberMeServices的key保持一致
|
||||
// // .rememberMe().key("testallKey").and()
|
||||
// // 关闭csrf
|
||||
// .and().cors().and().csrf().disable()
|
||||
// // X-Frame-Options: SAMEORIGIN 表示该页面可以在相同域名页面的 frame 中展示
|
||||
// .headers().frameOptions().sameOrigin();
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// auth.userDetailsService(userDetailsServiceImpl())
|
||||
// .passwordEncoder(new PasswordEncoder() {
|
||||
// @Override
|
||||
// public String encode(CharSequence charSequence) {
|
||||
// return DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
|
||||
// }
|
||||
// @Override
|
||||
// public boolean matches(CharSequence charSequence, String s) {
|
||||
// String digestAsHex = DigestUtils.md5DigestAsHex(charSequence.toString().getBytes());
|
||||
// return Objects.equals(s, digestAsHex);
|
||||
// }
|
||||
// }).and().authenticationProvider(rememberMeAuthenticationProvider());
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public DocDetailsServiceImpl userDetailsServiceImpl() {
|
||||
// return new DocDetailsServiceImpl();
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public DocUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter() throws Exception {
|
||||
// DocUsernamePasswordAuthenticationFilter myFilter = new DocUsernamePasswordAuthenticationFilter();
|
||||
// myFilter.setAuthenticationManager(authenticationManagerBean());
|
||||
// myFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler());
|
||||
// myFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
|
||||
// myFilter.setRememberMeServices(tokenBasedRememberMeServices());
|
||||
// return myFilter;
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public AuthenticationSuccessHandler authenticationSuccessHandler() {
|
||||
// return new SimpleUrlAuthenticationSuccessHandler("/login/success");
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public AuthenticationFailureHandler authenticationFailureHandler() {
|
||||
// return new SimpleUrlAuthenticationFailureHandler("/login/failure");
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public TokenBasedRememberMeServices tokenBasedRememberMeServices() {
|
||||
// TokenBasedRememberMeServices tbrms = new TokenBasedRememberMeServices("testallKey", userDetailsServiceImpl());
|
||||
// // 设置cookie过期时间为2天
|
||||
// tbrms.setTokenValiditySeconds(60 * 60 * 24 * 2);
|
||||
// // 设置checkbox的参数名为rememberMe(默认为remember-me),注意如果是ajax请求,参数名不是checkbox的name而是在ajax的data里
|
||||
// tbrms.setParameter("rememberMe");
|
||||
// tbrms.setAlwaysRemember(false);
|
||||
// return tbrms;
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public RememberMeAuthenticationProvider rememberMeAuthenticationProvider() {
|
||||
// RememberMeAuthenticationProvider rmap = new RememberMeAuthenticationProvider("testallKey");
|
||||
// return rmap;
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public RememberMeAuthenticationFilter rememberMeAuthenticationFilter() throws Exception {
|
||||
// RememberMeAuthenticationFilter myFilter = new RememberMeAuthenticationFilter(authenticationManagerBean(), tokenBasedRememberMeServices());
|
||||
// return myFilter;
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
package com.zyplayer.doc.manage.framework.exception;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.zyplayer.doc.core.exception.ConfirmException;
|
||||
import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
import com.zyplayer.doc.core.json.ResponseJson;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -20,10 +16,11 @@ import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.zyplayer.doc.core.exception.ConfirmException;
|
||||
import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
import com.zyplayer.doc.core.json.ResponseJson;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
@@ -44,8 +41,6 @@ public class GlobalHandlerExceptionResolver extends SimpleMappingExceptionResolv
|
||||
DocResponseJson<Object> responseJson = null;
|
||||
if (ex instanceof ConfirmException) {// 提示性异常
|
||||
responseJson = DocResponseJson.warn(ex.getMessage());
|
||||
} else if (ex instanceof AccessDeniedException) {// 没权限
|
||||
responseJson = DocResponseJson.warn("您没有权限访问本接口");
|
||||
} else {// 其他异常
|
||||
responseJson = DocResponseJson.warn("系统错误");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.zyplayer.doc.manage.framework.interceptor;
|
||||
|
||||
import com.zyplayer.doc.core.json.HttpConst;
|
||||
import com.zyplayer.doc.data.config.security.DocUserUtil;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -7,6 +9,7 @@ import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@@ -24,6 +27,7 @@ public class RequestInfoInterceptor implements HandlerInterceptor {
|
||||
*/
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3) {
|
||||
DocUserUtil.clean();
|
||||
long startTime = startTimeThreadLocal.get();
|
||||
long totalTime = System.currentTimeMillis() - startTime;// 结束时间
|
||||
logger.info("总耗时:{}ms,URI:{}", totalTime, request.getRequestURI());
|
||||
@@ -39,6 +43,7 @@ public class RequestInfoInterceptor implements HandlerInterceptor {
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) {
|
||||
startTimeThreadLocal.set(System.currentTimeMillis());
|
||||
// 指定域名可跨域访问
|
||||
String originRegex = ".*\\.zyplayer\\.com(:\\d+|)$";
|
||||
String origin = request.getHeader("Origin");
|
||||
if (StringUtils.isNotBlank(origin) && origin.toLowerCase().matches(originRegex)) {
|
||||
@@ -48,7 +53,41 @@ public class RequestInfoInterceptor implements HandlerInterceptor {
|
||||
response.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
response.setContentType("application/json; charset=utf-8");
|
||||
}
|
||||
String accessToken = getCookieValueByRequest(request, HttpConst.ACCESS_TOKEN);
|
||||
DocUserUtil.setAccessToken(accessToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取cookie
|
||||
*
|
||||
* @param request
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static Cookie getCookieByRequest(HttpServletRequest request, String name) {
|
||||
if (StringUtils.isEmpty(name)) {
|
||||
return null;
|
||||
}
|
||||
Cookie[] cookies = request.getCookies();
|
||||
for (int i = 0; (cookies != null) && (i < cookies.length); i++) {
|
||||
Cookie cookie = cookies[i];
|
||||
if (name.equals(cookie.getName())) {
|
||||
return cookie;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取cookie值
|
||||
*
|
||||
* @param request
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static String getCookieValueByRequest(HttpServletRequest request, String name) {
|
||||
Cookie cookie = getCookieByRequest(request, name);
|
||||
return cookie == null ? null : cookie.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@ package com.zyplayer.doc.manage.web.manage;
|
||||
|
||||
import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
import com.zyplayer.doc.core.json.ResponseJson;
|
||||
import com.zyplayer.doc.data.aspect.AuthMan;
|
||||
import com.zyplayer.doc.data.config.security.DocUserDetails;
|
||||
import com.zyplayer.doc.data.config.security.DocUserUtil;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.AuthInfo;
|
||||
import com.zyplayer.doc.data.service.manage.AuthInfoService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -17,7 +17,7 @@ import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth/info")
|
||||
@PreAuthorize("hasAuthority('AUTH_MANAGE')")
|
||||
@AuthMan("AUTH_MANAGE")
|
||||
public class AuthInfoController {
|
||||
|
||||
@Autowired
|
||||
|
||||
@@ -1,66 +1,77 @@
|
||||
package com.zyplayer.doc.manage.web.manage;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.WebAttributes;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.savedrequest.SavedRequest;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
import com.zyplayer.doc.data.config.security.DocUserDetails;
|
||||
import com.zyplayer.doc.data.config.security.DocUserUtil;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.AuthInfo;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.UserAuth;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.UserInfo;
|
||||
import com.zyplayer.doc.data.service.manage.AuthInfoService;
|
||||
import com.zyplayer.doc.data.service.manage.UserAuthService;
|
||||
import com.zyplayer.doc.data.service.manage.UserInfoService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
public class LoginController {
|
||||
private RequestCache requestCache = new HttpSessionRequestCache();
|
||||
|
||||
@Autowired
|
||||
private UserInfoService userInfoService;
|
||||
@Autowired
|
||||
private UserAuthService userAuthService;
|
||||
@Autowired
|
||||
private AuthInfoService authInfoService;
|
||||
|
||||
@GetMapping(value = "/login")
|
||||
public ModelAndView loginPage(HttpServletRequest request) {
|
||||
public ModelAndView loginPage() {
|
||||
return new ModelAndView("/statics/manage/login.html");
|
||||
}
|
||||
|
||||
// @PostMapping(value = "/logout")
|
||||
// public DocResponseJson<Object> logout(HttpServletRequest request) {
|
||||
//
|
||||
// return DocResponseJson.ok();
|
||||
// }
|
||||
|
||||
/**
|
||||
* 如果是访问受限页面后,跳转到登录页的,则在targetUrl保存之前受限页面的路径,供页面调用
|
||||
*
|
||||
* @param request
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@GetMapping(value = "/login/success")
|
||||
public DocResponseJson<String> loginSuccess(HttpServletRequest request, HttpServletResponse response) {
|
||||
SavedRequest savedRequest = requestCache.getRequest(request, response);
|
||||
String targetUrl = null;
|
||||
if (savedRequest != null) {
|
||||
targetUrl = savedRequest.getRedirectUrl();
|
||||
@PostMapping(value = "/login")
|
||||
public DocResponseJson<Object> login(String userNo, HttpServletResponse response) {
|
||||
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("user_no", userNo);
|
||||
UserInfo userInfo = userInfoService.getOne(queryWrapper);
|
||||
if (userInfo == null) {
|
||||
return DocResponseJson.warn("用户名'" + userNo + "'没有找到!");
|
||||
}
|
||||
if (StringUtils.isBlank(targetUrl)) {
|
||||
targetUrl = "/";
|
||||
QueryWrapper<UserAuth> authWrapper = new QueryWrapper<>();
|
||||
authWrapper.eq("user_id", userInfo.getId()).eq("del_flag", "0");
|
||||
List<UserAuth> userAuthList = userAuthService.list(authWrapper);
|
||||
Set<String> userAuthSet = Collections.emptySet();
|
||||
if (userAuthList != null && userAuthList.size() > 0) {
|
||||
List<Long> authIdList = userAuthList.stream().map(UserAuth::getAuthId).collect(Collectors.toList());
|
||||
Collection<AuthInfo> authInfoList = authInfoService.listByIds(authIdList);
|
||||
userAuthSet = authInfoList.stream().map(AuthInfo::getAuthName).collect(Collectors.toSet());
|
||||
}
|
||||
return DocResponseJson.ok(targetUrl);
|
||||
String accessToken = RandomUtil.simpleUUID();
|
||||
DocUserDetails userDetails = new DocUserDetails(userInfo.getId(), userInfo.getUserName(), userInfo.getPassword(), true, userAuthSet);
|
||||
DocUserUtil.setCurrentUser(accessToken, userDetails);
|
||||
// 放入cookie,过期时间:24小时
|
||||
Cookie cookie = new Cookie("accessToken", accessToken);
|
||||
cookie.setPath("/");
|
||||
cookie.setDomain("zyplayer.com");
|
||||
cookie.setMaxAge(60 * 60 * 24);
|
||||
response.addCookie(cookie);
|
||||
return DocResponseJson.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取异常信息返回给页面
|
||||
*
|
||||
* @param request
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@GetMapping(value = "/login/failure")
|
||||
public DocResponseJson<String> loginFailure(HttpServletRequest request, HttpServletResponse response) {
|
||||
AuthenticationException ae = (AuthenticationException) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
|
||||
return DocResponseJson.warn(ae.getMessage());
|
||||
@PostMapping(value = "/logout")
|
||||
public DocResponseJson<Object> logout() {
|
||||
DocUserUtil.logout();
|
||||
return DocResponseJson.ok();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.zyplayer.doc.manage.web.manage;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
import com.zyplayer.doc.core.json.ResponseJson;
|
||||
import com.zyplayer.doc.data.aspect.AuthMan;
|
||||
import com.zyplayer.doc.data.config.security.DocUserDetails;
|
||||
import com.zyplayer.doc.data.config.security.DocUserUtil;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.AuthInfo;
|
||||
@@ -10,7 +11,6 @@ import com.zyplayer.doc.data.repository.manage.entity.UserAuth;
|
||||
import com.zyplayer.doc.data.service.manage.AuthInfoService;
|
||||
import com.zyplayer.doc.data.service.manage.UserAuthService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -21,7 +21,7 @@ import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/user/auth")
|
||||
@PreAuthorize("hasAuthority('AUTH_ASSIGN')")
|
||||
@AuthMan("AUTH_ASSIGN")
|
||||
public class UserAuthController {
|
||||
|
||||
@Autowired
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.zyplayer.doc.manage.web.manage;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.zyplayer.doc.core.json.DocResponseJson;
|
||||
import com.zyplayer.doc.core.json.ResponseJson;
|
||||
import com.zyplayer.doc.data.aspect.AuthMan;
|
||||
import com.zyplayer.doc.data.config.security.DocUserDetails;
|
||||
import com.zyplayer.doc.data.config.security.DocUserUtil;
|
||||
import com.zyplayer.doc.data.repository.manage.entity.AuthInfo;
|
||||
@@ -15,7 +16,6 @@ import com.zyplayer.doc.manage.web.manage.vo.AuthInfoVo;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.dozer.Mapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.util.DigestUtils;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -27,7 +27,7 @@ import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/user/info")
|
||||
@PreAuthorize("hasAuthority('USER_MANAGE')")
|
||||
@AuthMan("USER_MANAGE")
|
||||
public class UserInfoController {
|
||||
|
||||
@Autowired
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
</template>
|
||||
<el-container v-else>
|
||||
<el-aside width="200px">
|
||||
<div style="padding: 10px;" v-show="leftCollapse">
|
||||
<div style="padding: 10px;height: 100%;box-sizing: border-box;background: #fafafa;" v-show="leftCollapse">
|
||||
<div style="margin-bottom: 10px;">
|
||||
<el-select v-model="choiceSpace" @change="spaceChangeEvents" filterable placeholder="选择空间" style="width: 100%;">
|
||||
<el-option-group label="">
|
||||
@@ -32,14 +32,30 @@
|
||||
</el-tree>
|
||||
</div>
|
||||
</el-aside>
|
||||
<el-main>
|
||||
<router-view></router-view>
|
||||
</el-main>
|
||||
<el-container>
|
||||
<el-header>
|
||||
<!--<el-switch v-model="isCollapse" ></el-switch>-->
|
||||
<i class="el-icon-menu icon-collapse" @click="leftCollapse = !leftCollapse;"></i>
|
||||
<!--<div class="logo" @click="aboutDialogVisible = true">zyplayer-doc-wiki</div>-->
|
||||
<el-dropdown @command="userSettingDropdown" trigger="click">
|
||||
<i class="el-icon-setting" style="margin-right: 15px; font-size: 16px;cursor: pointer;color: #fff;"> </i>
|
||||
<el-dropdown-menu slot="dropdown">
|
||||
<el-dropdown-item command="aboutDoc">关于</el-dropdown-item>
|
||||
<el-dropdown-item command="" divided>我的资料</el-dropdown-item>
|
||||
<el-dropdown-item command="userSignOut">退出登录</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</el-dropdown>
|
||||
</el-header>
|
||||
<el-main style="padding: 0;">
|
||||
<router-view></router-view>
|
||||
</el-main>
|
||||
</el-container>
|
||||
</el-container>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import global from './common/config/global'
|
||||
var app;
|
||||
export default {
|
||||
data() {
|
||||
@@ -101,13 +117,18 @@
|
||||
},
|
||||
mounted: function () {
|
||||
app = this;
|
||||
global.vue.$app = this;
|
||||
this.loadSpaceList();
|
||||
},
|
||||
methods: {
|
||||
sendMsgToParent: function (msg) {
|
||||
alert(msg)
|
||||
},
|
||||
createWiki() {
|
||||
|
||||
},
|
||||
searchByKeywords() {
|
||||
this.sendMsgToParent();
|
||||
this.$refs.wikiPageTree.filter(app.searchKeywords);
|
||||
},
|
||||
handleNodeClick(data) {
|
||||
@@ -226,6 +247,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
userSettingDropdown(command) {
|
||||
console.log("command:" + command);
|
||||
if (command == 'userSignOut') {
|
||||
// this.userSignOut();
|
||||
} else if (command == 'aboutDoc') {
|
||||
app.aboutDialogVisible = true;
|
||||
} else {
|
||||
// Toast.notOpen();
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -240,4 +271,7 @@
|
||||
#app, .el-container, .el-menu {
|
||||
height: 100%;
|
||||
}
|
||||
.el-header {background-color: #409EFF; color: #333; line-height: 40px; text-align: right;height: 40px !important;}
|
||||
.icon-collapse{float: left;font-size: 25px;color: #aaa;margin-top: 8px;cursor: pointer;}
|
||||
.icon-collapse:hover{color: #eee;}
|
||||
</style>
|
||||
|
||||
@@ -30,8 +30,8 @@ var _evt = function () {
|
||||
|
||||
var _fn = {
|
||||
href: href,
|
||||
HOST: EVT + 'local.zyplayer.com:8083/zyplayer-doc-manage', //这里设置接口域名
|
||||
HOST1: EVT + 'local.zyplayer.com:8083', //设置多个接口域名
|
||||
HOST: EVT + 'local.zyplayer.com:8084', //这里设置接口域名
|
||||
HOST1: EVT + 'local.zyplayer.com:8084', //设置多个接口域名
|
||||
mixUrl: function (host, url) {
|
||||
var p;
|
||||
if (!host || !url || _fn.isEmptyObject(url)) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
const user = {
|
||||
isLogin: true,
|
||||
};
|
||||
const app = {};
|
||||
const vue = {};
|
||||
const fullscreen = false;
|
||||
|
||||
export default {
|
||||
app,
|
||||
vue,
|
||||
user,
|
||||
fullscreen,
|
||||
}
|
||||
|
||||
@@ -19,12 +19,12 @@ export default {
|
||||
},
|
||||
validateResult: function (res, callback) {
|
||||
if (res.data.errCode == 400) {
|
||||
global.app.$message('请先登录');
|
||||
global.app.$router.push("/user/login");
|
||||
global.vue.$message('请先登录');
|
||||
global.vue.$router.push("/user/login");
|
||||
} else if (res.data.errCode == 402) {
|
||||
global.app.$router.push("/common/noAuth");
|
||||
global.vue.$router.push("/common/noAuth");
|
||||
} else if (res.data.errCode !== 200) {
|
||||
global.app.$message(res.data.errMsg || "未知错误");
|
||||
global.vue.$message(res.data.errMsg || "未知错误");
|
||||
} else {
|
||||
if (typeof callback == 'function') {
|
||||
callback(res.data);
|
||||
@@ -34,7 +34,7 @@ export default {
|
||||
post: function (url, param, callback) {
|
||||
param = param || {};
|
||||
param.accessToken = this.getAccessToken();
|
||||
global.app.axios({
|
||||
global.vue.axios({
|
||||
method: "post",
|
||||
url: url,
|
||||
headers: {'Content-type': 'application/x-www-form-urlencoded'},
|
||||
|
||||
@@ -7,14 +7,14 @@ import global from '../../config/global'
|
||||
*/
|
||||
export default {
|
||||
notOpen: function () {
|
||||
global.app.$message({
|
||||
global.vue.$message({
|
||||
message: '该功能暂未开放,敬请期待!',
|
||||
type: 'warning',
|
||||
showClose: true
|
||||
});
|
||||
},
|
||||
success: function (msg, time) {
|
||||
global.app.$message({
|
||||
global.vue.$message({
|
||||
message: msg,
|
||||
duration: time || 3000,
|
||||
type: 'success',
|
||||
@@ -22,7 +22,7 @@ export default {
|
||||
});
|
||||
},
|
||||
warn: function (msg, time) {
|
||||
global.app.$message({
|
||||
global.vue.$message({
|
||||
message: msg,
|
||||
duration: time || 3000,
|
||||
type: 'warning',
|
||||
@@ -30,7 +30,7 @@ export default {
|
||||
});
|
||||
},
|
||||
error: function (msg, time) {
|
||||
global.app.$message({
|
||||
global.vue.$message({
|
||||
message: msg,
|
||||
duration: time || 3000,
|
||||
type: 'error',
|
||||
|
||||
@@ -50,7 +50,7 @@ new Vue({
|
||||
router,
|
||||
render(h) {
|
||||
var app = h(App);
|
||||
global.app = app.context;
|
||||
global.vue = app.context;
|
||||
return app;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,18 +1,34 @@
|
||||
<template>
|
||||
<div>欢迎使用wiki文档管理工具</div>
|
||||
<div v-on:click="sendMsgToParent">
|
||||
<div style="margin-top: 30px;color: #666; text-align: center; font-size: 30px;">欢迎使用在线文档</div>
|
||||
<div style="margin-top: 30px;color: #666; text-align: center;">
|
||||
{{nowSpaceShow.name}}
|
||||
<span v-show="nowSpaceShow.spaceExplain && nowSpaceShow.spaceExplain.length > 0"> · {{nowSpaceShow.spaceExplain}}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import global from '../../common/config/global'
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {};
|
||||
return {
|
||||
nowSpaceShow: {
|
||||
name: '',
|
||||
spaceExplain: '',
|
||||
}
|
||||
};
|
||||
},
|
||||
mounted: function () {
|
||||
// this.getUserInfo();
|
||||
},
|
||||
methods: {
|
||||
getUserInfo: function () {
|
||||
this.common.post(this.apilist1.getUserInfo, {}, function (json) {});
|
||||
// this.common.post(this.apilist1.getUserInfo, {}, function (json) {});
|
||||
},
|
||||
sendMsgToParent: function () {
|
||||
global.vue.$app.sendMsgToParent("xxx");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user