♻️ Refactoring code. @SneakyThrows

This commit is contained in:
冷冷 committed 2019-01-19 22:35:17 +08:00
1 parent f80d6d51e4
commit 271fefcdfc
37 files changed
+206 -171

No files matched your search

@@ -22,6 +22,7 @@ import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.security.exception.PigxAuth2Exception;
import lombok.SneakyThrows;
import java.io.IOException;
@@ -37,7 +38,8 @@ public class PigxAuth2ExceptionSerializer extends StdSerializer<PigxAuth2Excepti
}
@Override
public void serialize(PigxAuth2Exception value, JsonGenerator gen, SerializerProvider provider) throws IOException {
@SneakyThrows
public void serialize(PigxAuth2Exception value, JsonGenerator gen, SerializerProvider provider) {
gen.writeStartObject();
gen.writeObjectField("code", CommonConstants.FAIL);
gen.writeStringField("msg", value.getMessage());
@@ -18,6 +18,7 @@
package com.pig4cloud.pigx.common.security.component;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -56,10 +57,10 @@ public class PigxResourceServerConfigurerAdapter extends ResourceServerConfigure
* 默认的配置,对外暴露
*
* @param httpSecurity
* @throws Exception
*/
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
@SneakyThrows
public void configure(HttpSecurity httpSecurity) {
//允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
httpSecurity.headers().frameOptions().disable();
ExpressionUrlAuthorizationConfigurer<HttpSecurity>
@@ -21,6 +21,7 @@ import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@@ -43,8 +44,9 @@ import javax.servlet.http.HttpServletRequest;
public class PigxSecurityInnerAspect {
private final HttpServletRequest request;
@SneakyThrows
@Around("@annotation(inner)")
public Object around(ProceedingJoinPoint point, Inner inner) throws Throwable {
public Object around(ProceedingJoinPoint point, Inner inner) {
String header = request.getHeader(SecurityConstants.FROM);
if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
log.warn("访问接口 {} 没有权限", point.getSignature().getName());
@@ -45,7 +45,7 @@ public class PigxWebResponseExceptionTranslator implements WebResponseExceptionT
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
public ResponseEntity<OAuth2Exception> translate(Exception e) {
// Try to extract a SpringSecurityException from the stacktrace
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
@@ -22,6 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
@@ -46,8 +47,9 @@ public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint
private final ObjectMapper objectMapper;
@Override
@SneakyThrows
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
AuthenticationException authException) {
response.setCharacterEncoding(CommonConstants.UTF8);
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
R<String> result = new R<>();
@@ -20,12 +20,12 @@ package com.pig4cloud.pigx.common.security.mobile;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
@@ -62,11 +62,12 @@ public class MobileAuthenticationFilter extends AbstractAuthenticationProcessing
}
@Override
@SneakyThrows
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
HttpServletResponse response) {
if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
"Authentication method not supported: " + request.getMethod());
}
String mobile = obtainMobile(request);
@@ -93,11 +94,11 @@ public class MobileAuthenticationFilter extends AbstractAuthenticationProcessing
logger.debug("Authentication request failed: " + failed);
eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
try {
authenticationEntryPoint.commence(request, response,
new UsernameNotFoundException(failed.getMessage(), failed));
new UsernameNotFoundException(failed.getMessage(), failed));
} catch (Exception e) {
logger.error("authenticationEntryPoint handle error:{}", failed);
}
@@ -21,12 +21,12 @@ import com.pig4cloud.pigx.common.security.component.PigxPreAuthenticationChecks;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
@@ -47,7 +47,8 @@ public class MobileAuthenticationProvider implements AuthenticationProvider {
private PigxUserDetailsService userDetailsService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
@SneakyThrows
public Authentication authenticate(Authentication authentication) {
MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
String principal = mobileAuthenticationToken.getPrincipal().toString();
@@ -17,6 +17,7 @@
package com.pig4cloud.pigx.common.security.mobile;
import lombok.SneakyThrows;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
@@ -30,46 +31,47 @@ import java.util.Collection;
*/
public class MobileAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object principal;
private final Object principal;
public MobileAuthenticationToken(String mobile) {
super(null);
this.principal = mobile;
setAuthenticated(false);
}
public MobileAuthenticationToken(String mobile) {
super(null);
this.principal = mobile;
setAuthenticated(false);
}
public MobileAuthenticationToken(Object principal,
public MobileAuthenticationToken(Object principal,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
@Override
@SneakyThrows
public void setAuthenticated(boolean isAuthenticated) {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false);
}
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
}
}
@@ -18,6 +18,7 @@
package com.pig4cloud.pigx.common.security.service;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import lombok.SneakyThrows;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
@@ -45,8 +46,9 @@ public class PigxClientDetailsService extends JdbcClientDetailsService {
* @throws InvalidClientException
*/
@Override
@SneakyThrows
@Cacheable(value = SecurityConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null")
public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
public ClientDetails loadClientByClientId(String clientId) {
return super.loadClientByClientId(clientId);
}
}
@@ -26,6 +26,7 @@ import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
@@ -60,7 +61,8 @@ public class PigxUserDetailsServiceImpl implements PigxUserDetailsService {
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
@SneakyThrows
public UserDetails loadUserByUsername(String username) {
Cache cache = cacheManager.getCache("user_details");
if (cache != null && cache.get(username) != null) {
return (PigxUser) cache.get(username).get();
@@ -81,7 +83,8 @@ public class PigxUserDetailsServiceImpl implements PigxUserDetailsService {
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserBySocial(String inStr) throws UsernameNotFoundException {
@SneakyThrows
public UserDetails loadUserBySocial(String inStr) {
return getUserDetails(remoteUserService.social(inStr, SecurityConstants.FROM_IN));
}
@@ -19,6 +19,7 @@ package com.pig4cloud.pigx.common.security.util;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
@@ -43,8 +44,8 @@ public class AuthUtils {
* @throws RuntimeException if the Basic header is not present or is not valid
* Base64
*/
public String[] extractAndDecodeHeader(String header)
throws IOException {
@SneakyThrows
public String[] extractAndDecodeHeader(String header) {
byte[] base64Token = header.substring(6).getBytes("UTF-8");
byte[] decoded;
@@ -70,10 +71,9 @@ public class AuthUtils {
*
* @param request
* @return
* @throws IOException
*/
public String[] extractAndDecodeHeader(HttpServletRequest request)
throws IOException {
@SneakyThrows
public String[] extractAndDecodeHeader(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header == null || !header.startsWith(BASIC_)) {