代码优化,接口放行统一使用@AnonymousAccess,邮箱验证优化

pull/214/head
dqjdda 2019-11-29 10:05:38 +08:00
parent a635009499
commit faa93f4bf8
7 changed files with 16 additions and 33 deletions

View File

@ -61,10 +61,8 @@ public @interface Query {
* 使sql * 使sql
*/ */
enum Join { enum Join {
/** jie 2019-6-4 13:18:30 左连接 */ /** jie 2019-6-4 13:18:30 左右连接 */
LEFT LEFT, RIGHT
/** jie 2019-6-4 13:18:30 右连接 */
, RIGHT
} }
} }

View File

@ -14,11 +14,6 @@ import java.util.stream.Collectors;
public class ElPermissionConfig { public class ElPermissionConfig {
public Boolean check(String ...permissions){ public Boolean check(String ...permissions){
// 如果是匿名访问的,就放行
String anonymous = "anonymous";
if(Arrays.asList(permissions).contains(anonymous)){
return true;
}
// 获取当前用户的所有权限 // 获取当前用户的所有权限
List<String> elPermissions = SecurityUtils.getUserDetails().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); List<String> elPermissions = SecurityUtils.getUserDetails().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
// 判断当前用户的所有权限是否包含接口上定义的权限 // 判断当前用户的所有权限是否包含接口上定义的权限

View File

@ -1,6 +1,5 @@
package me.zhengjie.utils; package me.zhengjie.utils;
import org.springframework.util.DigestUtils;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory; import javax.crypto.SecretKeyFactory;

View File

@ -2,6 +2,7 @@ package me.zhengjie.utils;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
/** /**
* *
@ -23,11 +24,7 @@ public class ValidationUtil{
/** /**
* *
*/ */
public static boolean isEmail(String string) { public static boolean isEmail(String email) {
if (string == null){ return new EmailValidator().isValid(email, null);
return false;
}
String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
return string.matches(regEx1);
} }
} }

View File

@ -4,11 +4,9 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import me.zhengjie.annotation.AnonymousAccess; import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Limit; import me.zhengjie.annotation.Limit;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
/** /**
@ -26,7 +24,7 @@ public class LimitController {
* 60访 10redis limit_test * 60访 10redis limit_test
*/ */
@GetMapping @GetMapping
@PreAuthorize("@el.check('anonymous')") @AnonymousAccess
@ApiOperation("测试") @ApiOperation("测试")
@Limit(key = "test", period = 60, count = 10, name = "testLimit", prefix = "limit") @Limit(key = "test", period = 60, count = 10, name = "testLimit", prefix = "limit")
public int testLimit() { public int testLimit() {

View File

@ -6,7 +6,6 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@ -48,34 +47,31 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean @Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() { GrantedAuthorityDefaults grantedAuthorityDefaults() {
// Remove the ROLE_ prefix // 去除 ROLE_ 前缀
return new GrantedAuthorityDefaults(""); return new GrantedAuthorityDefaults("");
} }
@Bean @Bean
public PasswordEncoder passwordEncoder() { public PasswordEncoder passwordEncoder() {
// 密码加密方式
return new BCryptPasswordEncoder(); return new BCryptPasswordEncoder();
} }
@Override @Override
protected void configure(HttpSecurity httpSecurity) throws Exception { protected void configure(HttpSecurity httpSecurity) throws Exception {
// 搜寻 匿名标记 url PreAuthorize("hasAnyRole('anonymous')") 和 PreAuthorize("@el.check('anonymous')") 和 AnonymousAccess // 搜寻匿名标记 url @AnonymousAccess
Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods(); Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
Set<String> anonymousUrls = new HashSet<>(); Set<String> anonymousUrls = new HashSet<>();
for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) { for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
HandlerMethod handlerMethod = infoEntry.getValue(); HandlerMethod handlerMethod = infoEntry.getValue();
AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class); AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class); if (null != anonymousAccess) {
if (null != preAuthorize && preAuthorize.value().toLowerCase().contains("anonymous")) {
anonymousUrls.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
} else if (null != anonymousAccess && null == preAuthorize) {
anonymousUrls.addAll(infoEntry.getKey().getPatternsCondition().getPatterns()); anonymousUrls.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
} }
} }
httpSecurity httpSecurity
// 禁用 CSRF // 禁用 CSRF
.csrf().disable() .csrf().disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
// 授权异常 // 授权异常
.exceptionHandling() .exceptionHandling()
@ -95,6 +91,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.and() .and()
.authorizeRequests() .authorizeRequests()
// 静态资源等等
.antMatchers( .antMatchers(
HttpMethod.GET, HttpMethod.GET,
"/*.html", "/*.html",
@ -103,24 +100,23 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
"/**/*.js", "/**/*.js",
"/webSocket/**" "/webSocket/**"
).permitAll() ).permitAll()
// swagger start // swagger 文档
.antMatchers("/swagger-ui.html").permitAll() .antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll() .antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/webjars/**").permitAll() .antMatchers("/webjars/**").permitAll()
.antMatchers("/*/api-docs").permitAll() .antMatchers("/*/api-docs").permitAll()
// swagger end
// 文件 // 文件
.antMatchers("/avatar/**").permitAll() .antMatchers("/avatar/**").permitAll()
.antMatchers("/file/**").permitAll() .antMatchers("/file/**").permitAll()
// 阿里巴巴 druid
.antMatchers("/druid/**").permitAll() .antMatchers("/druid/**").permitAll()
// 放行OPTIONS请求 // 放行OPTIONS请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 自定义匿名访问所有url放行 允许 匿名和带权限以及登录用户访问 // 自定义匿名访问所有url放行 允许匿名和带权限以及登录用户访问
.antMatchers(anonymousUrls.toArray(new String[0])).permitAll() .antMatchers(anonymousUrls.toArray(new String[0])).permitAll()
// 所有请求都需要认证 // 所有请求都需要认证
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and().apply(securityConfigurerAdapter());
.apply(securityConfigurerAdapter());
} }
private TokenConfigurer securityConfigurerAdapter() { private TokenConfigurer securityConfigurerAdapter() {

View File

@ -97,8 +97,8 @@ public class AuthController {
return ResponseEntity.ok(jwtUser); return ResponseEntity.ok(jwtUser);
} }
@ApiOperation("获取验证码")
@AnonymousAccess @AnonymousAccess
@ApiOperation("获取验证码")
@GetMapping(value = "/code") @GetMapping(value = "/code")
public ResponseEntity getCode(){ public ResponseEntity getCode(){
// 算术类型 https://gitee.com/whvse/EasyCaptcha // 算术类型 https://gitee.com/whvse/EasyCaptcha