Commit 700a9ed2 authored by 孙 楠's avatar 孙 楠

重构一键登录,删除无效类

parent 58f99877
package cn.quantgroup.xyqb.config;
import static cn.quantgroup.xyqb.security.SecurityConstant.PROPERTY_PREFIX;
import cn.quantgroup.xyqb.security.AuthenticationAdapter;
import cn.quantgroup.xyqb.security.AuthenticationPrincipal;
import cn.quantgroup.xyqb.security.CustomerAuthenticationManager;
import cn.quantgroup.xyqb.urora.UroraAuthenticationManager;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* Created by Administrator on 2021/7/1 0001.
*/
@Configuration
@EnableConfigurationProperties(AuthenticationConfigurationProperties.class)
public class AuthenticationConfiguration {
private static final Logger logger = LoggerFactory.getLogger(AuthenticationConfiguration.class);
@Bean
public AuthenticationAdapter authenticationAdapter(AuthenticationConfigurationProperties properties) {
AuthenticationAdapter adapter = new AuthenticationAdapter();
Map<String, Map<String, String>> manager = properties.getManager();
Set<String> strings = manager.keySet();
try {
for (String key : strings) {
Map<String, String> map = manager.get(key);
Class<?> target = Thread.currentThread().getContextClassLoader().loadClass(map.get("target"));
//TODO: wait bean bean definition authentication manager
CustomerAuthenticationManager instance = (CustomerAuthenticationManager) target.newInstance();
instance.setPrincipal(new AuthenticationPrincipal(key));
Properties prop = new Properties();
map.forEach((k, v) -> {
if (k.startsWith(PROPERTY_PREFIX)) {
prop.setProperty(k.substring(PROPERTY_PREFIX.length()), v);
}
});
instance.setProperties(prop);
if (UroraAuthenticationManager.class.isInstance(instance)) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(Integer.parseInt(prop.getProperty("readTimeout", "10000")));
factory.setConnectTimeout(Integer.parseInt(prop.getProperty("connectTimeout", "20000")));
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(factory);
((UroraAuthenticationManager) instance).setRestTemplate(restTemplate);
}
instance.init();
logger.info("Authentication adapter register manager. {} - properties:{}", target, prop);
adapter.register(instance);
}
} catch (Exception e) {
logger.error("Authentication configuration initialization failed. " + e.getMessage(), e);
}
return adapter;
}
}
...@@ -25,8 +25,8 @@ public class RestTemplateConfig { ...@@ -25,8 +25,8 @@ public class RestTemplateConfig {
@Bean @Bean
public RestTemplate restTemplate() { public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(60 * 1000); requestFactory.setConnectTimeout(5 * 1000);
requestFactory.setReadTimeout(60 * 1000); requestFactory.setReadTimeout(15 * 1000);
RestTemplate restTemplate = new RestTemplate(requestFactory); RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate; return restTemplate;
......
package cn.quantgroup.xyqb.security;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.Authentication;
/**
* Created by Administrator on 2021/7/1 0001.
*/
public class AuthenticationAdapter {
public Map<String, CustomerAuthenticationManager> managers = new HashMap<>();
public AuthenticationAdapter() {
}
public void register(CustomerAuthenticationManager manager) {
managers.put(manager.getPrincipal().getName(), manager);
}
public CustomerAuthenticationManager getManager(String name){
return managers.get(name);
}
public Authentication authenticate(String principal, String credentials){
CustomerAuthenticationManager authenticationManager = getManager(principal);
if(authenticationManager==null){
throw new IllegalArgumentException("No such authentication manager. "+principal);
}
Authentication authenticate = authenticationManager.authenticate(credentials);
return authenticate;
}
}
package cn.quantgroup.xyqb.security;
import cn.quantgroup.xyqb.util.ApplicationContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.security.authentication.AuthenticationManager;
/**
* Created by Administrator on 2021/7/1 0001.
*/
@Slf4j
public class AuthenticationFactory {
public static AuthenticationManager getManager(String name){
AuthenticationManager manager = null;
try {
manager = ApplicationContextHolder.getBean(name.concat("AuthenticationManager"), AuthenticationManager.class);
if (manager == null) {
throw new IllegalArgumentException("No such authentication manager "+name);
}
} catch (BeansException e) {
throw new IllegalArgumentException("No such authentication manager "+name);
}
return manager;
}
}
package cn.quantgroup.xyqb.security; package cn.quantgroup.xyqb.security;
import cn.quantgroup.xyqb.urora.UroraAuthenticationToken;
import org.apache.commons.codec.binary.Base64;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/** /**
* Created by Administrator on 2021/6/25 0025. * Created by Administrator on 2021/6/25 0025.
...@@ -19,10 +24,6 @@ import org.springframework.stereotype.Component; ...@@ -19,10 +24,6 @@ import org.springframework.stereotype.Component;
public class AuthorizationAspect extends HttpAspect { public class AuthorizationAspect extends HttpAspect {
private static final Logger logger = LoggerFactory.getLogger(AuthorizationAspect.class); private static final Logger logger = LoggerFactory.getLogger(AuthorizationAspect.class);
@Autowired
private AuthenticationAdapter authenticationAdapter;
@Pointcut("@annotation(cn.quantgroup.xyqb.security.AuthorizationPoint)") @Pointcut("@annotation(cn.quantgroup.xyqb.security.AuthorizationPoint)")
private void pointCut() { private void pointCut() {
} }
...@@ -30,7 +31,8 @@ public class AuthorizationAspect extends HttpAspect { ...@@ -30,7 +31,8 @@ public class AuthorizationAspect extends HttpAspect {
@Around("pointCut()") @Around("pointCut()")
private Object around(ProceedingJoinPoint joinPoint) throws Throwable { private Object around(ProceedingJoinPoint joinPoint) throws Throwable {
AssentHeader header = getAssentHeader(); AssentHeader header = getAssentHeader();
Authentication authenticate = authenticationAdapter.authenticate(header.getAuthType(), header.getAuthMessage()); AuthenticationManager manager = AuthenticationFactory.getManager(header.getAuthType());
Authentication authenticate = manager.authenticate(getCredentials(header.getAuthMessage()));
if(!authenticate.isAuthenticated()){ if(!authenticate.isAuthenticated()){
throw new BadCredentialsException("not authorized"); throw new BadCredentialsException("not authorized");
} }
...@@ -42,4 +44,19 @@ public class AuthorizationAspect extends HttpAspect { ...@@ -42,4 +44,19 @@ public class AuthorizationAspect extends HttpAspect {
AuthorityManager.release(); AuthorityManager.release();
} }
} }
public Authentication getCredentials(String credentials) throws AuthenticationException {
String auth = ObjectUtils.getDisplayString(credentials);
if (StringUtils.isEmpty(credentials)) {
throw new BadCredentialsException("Authorization credentials does not look like urora. " + credentials);
}
auth = new String(Base64.decodeBase64(auth));
String[] strings = auth.split(":");
if (strings.length != 2) {
throw new BadCredentialsException("Authorization credentials does not look like urora. " + auth);
}
return new UroraAuthenticationToken(strings[0], strings[1]);
}
} }
package cn.quantgroup.xyqb.security;
import java.security.Principal;
import java.util.Properties;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;
/**
* Created by Administrator on 2021/7/1 0001.
*/
public abstract class CustomerAuthenticationManager implements AuthenticationManager {
private Principal principal;
private Properties properties = new Properties();
public CustomerAuthenticationManager() {
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public String getProperty(String key) {
return properties.getProperty(key);
}
public void setPrincipal(Principal principal) {
this.principal = principal;
}
public Principal getPrincipal() {
return principal;
}
public Authentication authenticate(String credentials) throws AuthenticationException {
Authentication auth = getCredentials(credentials);
if (StringUtils.isEmpty(auth.getPrincipal()) || StringUtils.isEmpty(auth.getCredentials())) {
throw new BadCredentialsException("authorization credentials does not look like urora. " + auth);
}
auth = authenticate(auth);
return auth;
}
public abstract void init();
public abstract Authentication getCredentials(String message) throws AuthenticationException;
public abstract Authentication authenticate(Authentication authentication) throws AuthenticationException;
}
package cn.quantgroup.xyqb.urora; package cn.quantgroup.xyqb.urora;
import cn.quantgroup.xyqb.security.CustomerAuthenticationManager;
import cn.quantgroup.xyqb.security.RSADecrypt; import cn.quantgroup.xyqb.security.RSADecrypt;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.apache.commons.codec.binary.Base64; import java.util.Objects;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
...@@ -14,72 +16,65 @@ import org.springframework.http.MediaType; ...@@ -14,72 +16,65 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.util.ObjectUtils; import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
/** /**
* Created by Administrator on 2021/7/1 0001. * Created by Administrator on 2021/7/1 0001.
*/ */
public class UroraAuthenticationManager extends CustomerAuthenticationManager { @Component(value="UroraAuthenticationManager")
public class UroraAuthenticationManager implements AuthenticationManager {
private static final Logger logger = LoggerFactory.getLogger(UroraAuthenticationManager.class); private static final Logger logger = LoggerFactory.getLogger(UroraAuthenticationManager.class);
@Autowired
private RestTemplate restTemplate; private RestTemplate restTemplate;
private HttpHeaders headers; private HttpHeaders headers;
public RestTemplate getRestTemplate() { @Value("${user.auth.manager.Urora.properties.authorization}")
return restTemplate; private String authorization;
}
public void setRestTemplate(RestTemplate restTemplate) { @Value("${user.auth.manager.Urora.properties.loginTokenVerify}")
this.restTemplate = restTemplate; private String appUrl;
}
@Override @Value("${user.auth.manager.Urora.properties.loginTokenVerifyWeb:https://api.verification.jpush.cn/v1/web/h5/loginTokenVerify}")
private String webUrl;
@Value("${user.auth.manager.Urora.properties.privateKey}")
private String key;
@PostConstruct
public void init() { public void init() {
this.headers = new HttpHeaders(); this.headers = new HttpHeaders();
this.headers.add("Authorization", getProperty("authorization")); this.headers.add("Authorization", authorization);
this.headers.setContentType(MediaType.APPLICATION_JSON_UTF8); this.headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters(); List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
MappingJackson2HttpMessageConverter stringHttpMessageConverter = new MappingJackson2HttpMessageConverter(); MappingJackson2HttpMessageConverter stringHttpMessageConverter = new MappingJackson2HttpMessageConverter();
stringHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON_UTF8, MediaType.TEXT_PLAIN)); stringHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON_UTF8, MediaType.TEXT_PLAIN));
messageConverters.add(stringHttpMessageConverter); messageConverters.add(stringHttpMessageConverter);
}
@Override
public Authentication getCredentials(String credentials) throws AuthenticationException {
String auth = ObjectUtils.getDisplayString(credentials);
if (StringUtils.isEmpty(credentials)) {
throw new BadCredentialsException("Authorization credentials does not look like urora. " + credentials);
}
auth = new String(Base64.decodeBase64(auth));
String[] strings = auth.split(":");
if (strings.length != 2) {
throw new BadCredentialsException("Authorization credentials does not look like urora. " + auth);
}
return new UroraAuthenticationToken(strings[0], strings[1]);
} }
@Override @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
HttpEntity<String> httpEntity = new HttpEntity<>("{\"loginToken\":\"" + authentication.getCredentials() + "\"}", headers); HttpEntity<String> httpEntity = new HttpEntity<>("{\"loginToken\":\"" + authentication.getCredentials() + "\"}", headers);
try { try {
ResponseEntity<UroraResponse> verify = restTemplate.postForEntity(getProperty("loginTokenVerify"), httpEntity, UroraResponse.class); String url = appUrl;
if(Objects.nonNull(authentication.getPrincipal()) && (authentication.getPrincipal().equals("operatorWeb"))){
url = webUrl;
}
ResponseEntity<UroraResponse> verify = restTemplate.postForEntity(url, httpEntity, UroraResponse.class);
if (HttpStatus.OK.equals(verify.getStatusCode())) { if (HttpStatus.OK.equals(verify.getStatusCode())) {
UroraResponse body = verify.getBody(); UroraResponse body = verify.getBody();
if (!body.getCode().equals("8000") || StringUtils.isEmpty(body.getPhone())) { if (!body.getCode().equals("8000") || StringUtils.isEmpty(body.getPhone())) {
logger.warn("Urora login token verify failed. {}", body); logger.warn("Urora login token verify failed. {}", body);
authentication.setAuthenticated(false); authentication.setAuthenticated(false);
} else { } else {
String decrypt = RSADecrypt.decrypt(body.getPhone(), getProperty("privateKey")); String decrypt = RSADecrypt.decrypt(body.getPhone(), key);
UroraAuthenticationToken token = new UroraAuthenticationToken(body.getId(), decrypt); UroraAuthenticationToken token = new UroraAuthenticationToken(body.getId(), decrypt);
token.setAuthenticated(true); token.setAuthenticated(true);
return token; return token;
......
...@@ -66,7 +66,7 @@ ...@@ -66,7 +66,7 @@
<!--<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="${logging.hibernate.level}"/>--> <!--<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="${logging.hibernate.level}"/>-->
<!--<logger name="org.hibernate.engine.QueryParameters" level="DEBUG"/>--> <!--<logger name="org.hibernate.engine.QueryParameters" level="DEBUG"/>-->
<!--<logger name="org.hibernate.SQL" level="DEBUG" />--> <!--<logger name="org.hibernate.SQL" level="DEBUG" />-->
<root level="DEBUG"> <root level="INFO">
<appender-ref ref="STDOUT"/> <appender-ref ref="STDOUT"/>
<appender-ref ref="ROLLINGFILE"/> <appender-ref ref="ROLLINGFILE"/>
</root> </root>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment