即使用户登录,访问也被拒绝,春季安全性

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了即使用户登录,访问也被拒绝,春季安全性相关的知识,希望对你有一定的参考价值。

我在我的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] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor-先前已认证:org.springframework。 security.authentication.AnonymousAuthenticationToken@dab9512f:主体:anonymousUser;凭证:[受保护];已验证:true;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@ffff4c9c:RemoteIp地址:172.16.1.1; SessionId:null;授予的权限:ROLE_ANONYMOUS2020-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,返回:-12020-04-23T11:01:46.393975556Z 11:01:46.393 [http-nio-80-exec-3] DEBUG org.springframework.security.web.access.ExceptionTranslationFilter-访问被拒绝(用户是匿名的);重定向到身份验证入口点2020-04-23T11:01:46.393991456Z org.springframework.security.access.AccessDeniedException:访问被拒绝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 at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)2020-04-23T11:01:46:394.856856Z在org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)2020-04-23T11:01:46.394012656Z at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)在org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)上的2020-04-23T11:01:46.394016356Z2020-04-23T11:01:46:394020156Z at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46.394023856Z at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)2020-04-23T11:01:46:394027656Z at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46.394031356Z at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)2020-04-23T11:01:46:394035156Z at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46:394038956Z at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)2020-04-23T11:01:46:394042856Z at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46:394046556Z位于org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)2020-04-23T11:01:46:394050356Z at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46:394054756Z at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)2020-04-23T11:01:46:394058656Z at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46.394062356Z在org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)2020-04-23T11:01:46:394.066156Z在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46:394.756756Z位于org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)2020-04-23T11:01:46:394.080756Z在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)上的2020-04-23T11:01:46.394084556Z2020-04-23T11:01:46:394088256Z at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)2020-04-23T11:01:46:394092156Z位于org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46:394095856Z at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)的2020-04-23T11:01:46.394099656Z2020-04-23T11:01:46:394103456Z at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:334)2020-04-23T11:01:46:394.107Z在org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)2020-04-23T11:01:46:394.956956在org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)2020-04-23T11:01:46:394.114656Z在org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)2020-04-23T11:01:46:394.456456在org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)的2020-04-23T11:01:46.394122156Z2020-04-23T11:01:46:394.125856Z位于org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)在org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)上的2020-04-23T11:01:46.394129556Z2020-04-23T11:01:46:394.133657Z在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)上的2020-04-23T11:01:46.394137457Zorg.apache.catalina.core.ApplicationFilterChain.doFilter的2020-04-23T11:01:46.394141157Z(ApplicationFilterChain.java:166)在org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)上的2020-04-23T11:01:46.394144957Z2020-04-23T11:01:46:394.148657Z在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)的2020-04-23T11:01:46.394152357Z2020-04-23T11:01:46.394156057Z at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)2020-04-23T11:01:46:394.159857Z在org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)2020-04-23T11:01:46:394.166457Z在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)的2020-04-23T11:01:46.394170157Zorg.apache.catalina.core.ApplicationFilterChain.doFilter的2020-04-23T11:01:46.394173957Z(ApplicationFilterChain.java:166)org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)的2020-04-23T11:01:46.394177757Zorg.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)的2020-04-23T11:01:46.394181757Z2020-04-23T11:01:46:394185657Z at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)的2020-04-23T11:01:46.394189357Z在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)上的2020-04-23T11:01:46.394193057Z2020-04-23T11:01:46:394196757Z位于org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)2020-04-23T11:01:46:394200457Z位于org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)org.apache.coyote.http11.Http11Processor.service上的2020-04-23T11:01:46.394204057Z(Http11Processor.java:408)2020-04-23T11:01:46:394.857Z在org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)2020-04-23T11:01:46:394211557Z at org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:834)2020-04-23T11:01:46:394215157Z位于org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1415)org.apache.tomcat.util.net.SocketProcessorBase.run上的2020-04-23T11:01:46.394219357Z(SocketProcessorBase.java:49)2020-04-23T11:01:46.394223057Z at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)2020-04-23T11:01:46.394226757Z at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:624)2020-04-23T11:01:46:394.457457Z在org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)2020-04-23T11:01:46.394234257Z at java.lang.Thread.run(Thread.java:748)

这是我的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
另一答案

[我的问题是因为该应用程序托管于azure服务,并且存在无法更改的请求超时230s,所以我将上传方法更改为异步上传,并且现在一切正常。

以上是关于即使用户登录,访问也被拒绝,春季安全性的主要内容,如果未能解决你的问题,请参考以下文章

JDBC连接:即使所有Previlleges都被授予,用户也被拒绝访问[关闭]

实施URL身份验证的春季安全性时拒绝URL访问

jsf spring安全访问被拒绝认证登录

FBSDKShareButton 即使在用户登录后也被禁用?

如何为用户创建无痛的安全春季社交注册/登录

登录成功后访问登录页面时出现Spring安全访问被拒绝消息。它应该重定向到默认页面