Skip to content

Commit

Permalink
代码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
elunez committed Nov 27, 2019
1 parent 2ecb82a commit fe812f1
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,6 @@ public ResponseEntity handleException(Throwable e){
return buildResponseEntity(ApiError.error(e.getMessage()));
}

/**
* 处理 接口无权访问异常AccessDeniedException
*/
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity handleAccessDeniedException(AccessDeniedException e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(FORBIDDEN.value(),e.getMessage()));
}

/**
* 处理自定义异常
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package me.zhengjie.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.file.Paths;

/**
* WebMvcConfigurer
Expand All @@ -24,20 +26,22 @@ public class ConfigurerAdapter implements WebMvcConfigurer {
@Value("${file.avatar}")
private String avatar;

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedOrigins("*")
.allowedMethods("GET","POST","PUT","DELETE");

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String avatarUtl = Paths.get(avatar).normalize().toUri().toASCIIString();
String pathUtl = Paths.get(path).normalize().toUri().toASCIIString();
String avatarUtl = "file:" + avatar.replace("\\","/");
String pathUtl = "file:" + path.replace("\\","/");
registry.addResourceHandler("/avatar/**").addResourceLocations(avatarUtl).setCachePeriod(0);
registry.addResourceHandler("/file/**").addResourceLocations(pathUtl).setCachePeriod(0);
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package me.zhengjie.modules.security.config;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.modules.security.security.JwtAccessDeniedHandler;
import me.zhengjie.modules.security.security.JwtAuthenticationEntryPoint;
import me.zhengjie.modules.security.security.JwtAuthorizationTokenFilter;
import me.zhengjie.modules.security.service.JwtUserDetailsServiceImpl;
Expand Down Expand Up @@ -39,6 +40,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {

private final JwtAuthenticationEntryPoint unauthorizedHandler;

private final JwtAccessDeniedHandler accessDeniedHandler;

private final JwtUserDetailsServiceImpl jwtUserDetailsService;

private final ApplicationContext applicationContext;
Expand All @@ -49,8 +52,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${jwt.header}")
private String tokenHeader;

public SecurityConfig(JwtAuthenticationEntryPoint unauthorizedHandler, JwtUserDetailsServiceImpl jwtUserDetailsService, JwtAuthorizationTokenFilter authenticationTokenFilter, ApplicationContext applicationContext) {
public SecurityConfig(JwtAuthenticationEntryPoint unauthorizedHandler, JwtAccessDeniedHandler accessDeniedHandler, JwtUserDetailsServiceImpl jwtUserDetailsService, JwtAuthorizationTokenFilter authenticationTokenFilter, ApplicationContext applicationContext) {
this.unauthorizedHandler = unauthorizedHandler;
this.accessDeniedHandler = accessDeniedHandler;
this.jwtUserDetailsService = jwtUserDetailsService;
this.authenticationTokenFilter = authenticationTokenFilter;
this.applicationContext = applicationContext;
Expand Down Expand Up @@ -100,6 +104,7 @@ protected void configure(HttpSecurity httpSecurity) throws Exception {
.csrf().disable()
// 授权异常
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler).and()
// 不创建会话
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
Expand All @@ -110,7 +115,7 @@ protected void configure(HttpSecurity httpSecurity) throws Exception {
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/webSocket/**"
"/webSocket/**"
).anonymous()
// swagger start
.antMatchers("/swagger-ui.html").permitAll()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package me.zhengjie.modules.security.security;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
//当用户在没有授权的情况下访问受保护的REST资源时,将调用此方法发送403 Forbidden响应
response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
}
}

0 comments on commit fe812f1

Please sign in to comment.