所有 Spring-Boot 应用程序始终显示弹出登录

Posted

技术标签:

【中文标题】所有 Spring-Boot 应用程序始终显示弹出登录【英文标题】:All Spring-Boot Application always show a popup login 【发布时间】:2018-02-01 11:28:10 【问题描述】:

我将 Spring 和 Spring Boot 框架与 Spring Security 一起用于具有简单 UI 的简单登录项目。在我所有的项目中,使用 STS,在启动我的应用程序并运行 localhost 地址没有错误后,我收到一个弹出登录窗口,而不是我的 html 页面。 如果我使用 user默认安全密码,我总是会得到一个 Whitelabel 错误页面作为结果。此外,如果我使用不正确的值,弹出窗口仍然存在,如果我使用默认访问值,我会收到此消息。

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Aug 23 20:14:22 CEST 2017
There was an unexpected error (type=Not Found, status=404).
No message available

这是一个简单的项目代码。正如您在项目结构中看到的那样,所有 html 文件都在模板文件夹中。我也尝试在我的 application.properties 文件中使用server.error.whitelabel.enabled=false。`

为什么html界面一直没有显示?

Project Structure

应用

package com.cyberdemon.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootUiLoginApplication 

    public static void main(String[] args) 
        SpringApplication.run(SpringbootUiLoginApplication.class, args);
    

安全配置

package config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableAutoConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter 

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception 
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password, enabled from users where username=?")
                .authoritiesByUsernameQuery("select username, role from user_roles where username=?");
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http.authorizeRequests().antMatchers("/", "/home").permitAll().antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
                .permitAll();
        http.exceptionHandling().accessDeniedPage("/403");
    


网络控制器

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WebController 

    @RequestMapping(value =  "/", "home" )
    public String home() 
        return "home";
    

    @RequestMapping(value =  "/welcome" )
    public String welcome() 
        return "welcome";
    

    @RequestMapping(value = "/admin")
    public String admin() 
        return "admin";
    

    @RequestMapping(value =  "/login" )
    public String login() 
        return "login";
    

    @RequestMapping(value = "/403")
    public String Error403() 
        return "403";
    


Pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cyberdemon.springboot</groupId>
    <artifactId>springboot_UI_Login</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_UI_Login</name>
    <description>Project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

属性

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=toor

控制台

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.6.RELEASE)

2017-08-23 19:57:05.949  INFO 7496 --- [           main] c.c.s.SpringbootUiLoginApplication       : Starting SpringbootUiLoginApplication on DESKTOP-CYBERDEMON with PID 7496 (started by GD in C:\Users\me\Documents\workspace-sts\springboot_ui_login)
2017-08-23 19:57:05.949  INFO 7496 --- [           main] c.c.s.SpringbootUiLoginApplication       : No active profile set, falling back to default profiles: default
2017-08-23 19:57:06.121  INFO 7496 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6cc7b4de: startup date [Wed Aug 23 19:57:06 CEST 2017]; root of context hierarchy
2017-08-23 19:57:07.293  INFO 7496 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-08-23 19:57:07.300  INFO 7496 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-08-23 19:57:07.300  INFO 7496 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-08-23 19:57:07.409  INFO 7496 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-08-23 19:57:07.409  INFO 7496 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1288 ms
2017-08-23 19:57:07.566  INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-08-23 19:57:07.566  INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-08-23 19:57:07.566  INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-08-23 19:57:07.566  INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-08-23 19:57:07.566  INFO 7496 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-08-23 19:57:07.566  INFO 7496 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-08-23 19:57:07.847  INFO 7496 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6cc7b4de: startup date [Wed Aug 23 19:57:06 CEST 2017]; root of context hierarchy
2017-08-23 19:57:07.894  INFO 7496 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "[/error]" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-08-23 19:57:07.894  INFO 7496 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "[/error],produces=[text/html]" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-08-23 19:57:07.925  INFO 7496 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-23 19:57:07.925  INFO 7496 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-23 19:57:07.956  INFO 7496 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-23 19:57:08.519  INFO 7496 --- [           main] b.a.s.AuthenticationManagerConfiguration : 

Using default security password: 21cf3953-b4e3-48ac-87fa-9041c41b3ff8

2017-08-23 19:57:08.567  INFO 7496 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2017-08-23 19:57:08.645  INFO 7496 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@12fcc71f, org.springframework.security.web.context.SecurityContextPersistenceFilter@5d43409a, org.springframework.security.web.header.HeaderWriterFilter@76563d26, org.springframework.security.web.authentication.logout.LogoutFilter@102ecc22, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@4eba373c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@6ede46f6, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@10a0fe30, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5679e96b, org.springframework.security.web.session.SessionManagementFilter@23b8d9f3, org.springframework.security.web.access.ExceptionTranslationFilter@261ea657, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@6cd64ee8]
2017-08-23 19:57:08.864  INFO 7496 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-08-23 19:57:08.911  INFO 7496 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-08-23 19:57:08.926  INFO 7496 --- [           main] c.c.s.SpringbootUiLoginApplication       : Started SpringbootUiLoginApplication in 3.164 seconds (JVM running for 3.428)
2017-08-23 19:57:24.008  INFO 7496 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-08-23 19:57:24.008  INFO 7496 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-08-23 19:57:24.021  INFO 7496 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 13 ms

【问题讨论】:

您要的网址是什么? 查看以下链接中的答案:***.com/questions/31134333/… @AmerQarabsa 我尝试了所有的 url 组合。 localhost:8080/login 应该是初始 url 或者只是 localhost:8080/ @AmitKBist,app.java 的正确位置看起来和我在那个问题中的位置一样!或不? ***.com/a/39017839/7148194 【参考方案1】:

跟进阿里的​​回答:

@SpringBootApplication 隐含@Configuration、@EnableAutoConfiguration 和@ComponentScan

所以,考虑改变:

@Configuration
@EnableAutoConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter

到:

@Component
public class SecurityConfig extends WebSecurityConfigurerAdapter

并在整个包更改中扫描 bean:

@SpringBootApplication
public class SpringbootUiLoginApplication

到:

@SpringBootApplication
@ComponentScan("com.cyberdemon")
public class SpringbootUiLoginApplication

【讨论】:

注释不会让我使用@符号,所以我希望这是有道理的: SpringBootApplication 等于 Configuration EnableAutoConfiguration ComponentScan 那些你不需要两次的注释。所以你可以从 SecurityConfig 中删除它们 你需要 SecurityConfig 是一个 bean,所以添加 @Component 是一种简单的方法来完成它。 ComponentScan 只扫描基础包和子包。如果要保留问题中的项目结构,则需要扫描所有包。我认为 ComponentScan("com.cyberdemon") 会做到这一点。【参考方案2】:

你需要重组你的包,使其属于你的 SpringbootUiLoginApplication 的包,或者使用 @ComponentScan 告诉 Spring Boot 在哪里可以找到你的 bean 类。

【讨论】:

确实,所有这些,包括控制器和安全配置都必须属于 com.cyberdemon.springboot 包,因为它是定义您的应用程序的地方。

以上是关于所有 Spring-Boot 应用程序始终显示弹出登录的主要内容,如果未能解决你的问题,请参考以下文章

AFNetworking 2.0 可达性警报始终显示

JQuery 弹出层,始终显示在屏幕正中间

mui怎样让popver弹出框始终显示在中间位置

winform如何让弹出窗口始终置于程序最顶层

iOS8 上的 UIPopoverPresentationController 始终全屏显示

Firebase 通知始终显示空白图标