java - 即使用户登录,访问也被拒绝弹簧安全
问题描述
我在我的 web 应用程序中使用 spring security 身份验证工作正常我在登录后被重定向到主页,登录的用户名显示在我的应用程序中,除了一件事之外一切都很好。我的应用程序中有一个上传方法,用户可以将视频上传到 Azure 存储,然后将 url 保存在数据库中这是上传方法
public String fileUpload(File fileUp, String fileN) {
try {
fileN = fileN.replace(" ", "_");
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionStringU);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
// Get a reference to a container.
// The container name must be lower case
CloudBlobContainer container = blobClient.getContainerReference("filescontainer");
System.out.println("exist " + container.exists());
// Create the container if it does not exist.
container.createIfNotExists();
// Allow Public Access
BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
// Include public access in the permissions object.
containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
// Set the permissions on the container.
container.uploadPermissions(containerPermissions);
// Create or overwrite the blob with contents from a local file.
CloudBlockBlob blob = container.getBlockBlobReference(fileN);
ServiceProperties serviceProperties = blob.getServiceClient().downloadServiceProperties();
serviceProperties.setDefaultServiceVersion("2019-07-07");
blob.getServiceClient().uploadServiceProperties(serviceProperties);
/* // Plan B
* RequestOptions RequestOptions =
* blob.getServiceClient().getDefaultRequestOptions();
* // <Can Set Timeout Here>
* RequestOptions.setTimeoutIntervalInMs(?);
*/
// Used StreamWriteSize to break the file into blocks to avoid timeout
blob.setStreamWriteSizeInBytes(1024*1024);
FileInputStream in = new FileInputStream(fileUp);
blob.upload(in, fileUp.length());
return containerUrl+fileN;
} catch (Exception e) {
// Output the stack trace.
e.printStackTrace();
}
return "";
}
这是我的上传控制器
@PostMapping("/addVideo")
public String uploadMultipleFiles(@RequestParam("vdLength") String vdLength,
@RequestParam("files1") MultipartFile files1){
byte[] buffer = new byte[4096];
int readByteCount = 0;
VideoFile vd = new VideoFile();
File target = new File(ownerID + fileNameVd + "_" + date.getTime() + ".mp4");
try(BufferedInputStream in= new BufferedInputStream(files1.getInputStream());
FileOutputStream out = new FileOutputStream(target)) {
while((readByteCount = in.read(buffer)) != -1) {
out.write(buffer, 0, readByteCount);
}
out.close();
}
vd.setVideoURL(new UploadAzurController().fileUpload(target,ownerID + fileNameVd + "_" + date.getTime() + ".mp4"));
target.delete();
videoService.addVideo(vd);}
上传有时会工作,有时会显示 502 - Web 服务器在充当网关或代理服务器时收到无效响应。我在堆栈跟踪中找到了这个:
2020-04-23T11:01:46.390408136Z 11:01:46.382 [http-nio-80-exec-3] 调试 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - 以前经过身份验证:org.springframework.security。 authentication.AnonymousAuthenticationToken@dab9512f:主体:anonymousUser;凭证:[受保护];已认证:真实;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@ffff4c9c:RemoteIpAddress:172.16.1.1;会话ID:空;授予权限:ROLE_ANONYMOUS 2020-04-23T11:01:46.391507942Z 11:01:46.391 [http-nio-80-exec-3] 调试 org.springframework.security.access.vote.AffirmativeBased - 投票者:org.springframework.security .web.access.expression.WebExpressionVoter@1928c84c,返回:-1 2020-04-23T11:01:46.393975556Z 11:01:46.393 [http-nio-80-exec-3] 调试 org.springframework.security.web。使用权。ExceptionTranslationFilter - 访问被拒绝(用户是匿名的);重定向到身份验证入口点 2020-04-23T11:01:46.393991456Z org.springframework.security.access.AccessDeniedException: Access is denied 2020-04-23T11:01:46.393996856Z at org.springframework.security.access.vote.AffirmativeBased .decide(AffirmativeBased.java:84) 2020-04-23T11:01:46.394001156Z at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) 2020-04-23T11:01:46.394005056Z在 org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) 2020-04-23T11:01:46.394008856Z 在 org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter( FilterSecurityInterceptor.java:91) 2020-04-23T11:01:46。
这是我的 sping 安全配置类
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Autowired
@Qualifier("datasource")
private DataSource dataSource;
public static Boolean anon;
@Value("${role.anonymous}")
public void setAnon(Boolean anon) {
this.anon = anon;
}
// Secure the endpoins with HTTP Basic authentication
@Override
protected void configure(HttpSecurity http) throws Exception {
if (anon) {
http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/Search/**").permitAll();
}
http.authorizeRequests()
.antMatchers("/manager*").hasAnyAuthority("ADMIN", "MANAGER")
.antMatchers("/uploadFile").hasAnyAuthority("ADMIN", "MANAGER")
.antMatchers("/resources/**").permitAll()
.antMatchers("/api/**").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/footer**").permitAll()
.antMatchers("/header**").permitAll()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and().csrf().disable().formLogin()
.loginPage("/login").defaultSuccessUrl("/");
}
@Bean
@Override
public UserDetailsService userDetailsServiceBean() {
try {
return super.userDetailsServiceBean();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Bean
public SwitchUserFilter switchUserFilter() {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(userDetailsServiceBean());
filter.setUsernameParameter("username");
filter.setSwitchUserUrl("/switch_user");
filter.setExitUserUrl("/switch_user_exit");
filter.setTargetUrl("/");
return filter;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).authoritiesByUsernameQuery(
"Select auth.username, auth.authority , 1 as enabled from (select A.username, A.authority from admin as A UNION select M.username, M.authority from manager as M UNION select U.username, U.authority from user as U UNION select R.username, R.authority from readeruser as R) auth WHERE auth.username = ? ")
.usersByUsernameQuery(
"Select auth.username, auth.password , 1 as enabled from (select A.username, A.password ,1 as enabled from admin as A UNION select M.username, M.password ,1 as enabled from manager as M UNION select U.username, U.password ,1 as enabled from user as U UNION select R.username, R.password ,1 as enabled from readeruser as R) auth WHERE auth.username = ? ");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
return firewall;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/*.css");
web.ignoring().antMatchers("/*.js");
web.ignoring().antMatchers("/*.png");
web.ignoring().antMatchers("/videos/*.mp4");
web.ignoring().antMatchers("/videos/*.png");
web.ignoring().antMatchers("/videos/*.vtt");
web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
}
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*"); // this allows all origin
config.addAllowedHeader("*"); // this allows all headers
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
上传失败后,我转到应用程序,发现用户仍然登录。我希望我提供了所有需要的信息,以便您可以帮助我。
解决方案
尝试增加文件大小上传。
#### File upload config ####
spring.servlet.multipart.max-file-size=xxMB/GB/etc
spring.servlet.multipart.max-request-size=xxMB/GB/etc
推荐阅读
- python - Python将立体声.flac转换为单声道
- excel - 如果在excel中嵌套
- python - 优化线性方程以获得最大最小值
- typescript - 如何将 VS Code 的大纲同步到编辑器中的当前位置
- ios - 可以将 Swift REPL 嵌入到 macOS 或 iOS 应用程序中吗?
- kubernetes - 如何在 GKE 中使用 ReadWriteMany 创建持久卷声明?
- jquery - 升级到 Bootstrap 4、jQuery 3.3.1 后 jQuery .show() /.hide() 无法正常工作
- html - 更改线条系列的颜色
- php - 如何通过 PHP 执行 Google Cloud Function?
- javascript - 材质 UI/React 错误