Spring Security 不断给出错误 404 GET /login [重复]

Posted

技术标签:

【中文标题】Spring Security 不断给出错误 404 GET /login [重复]【英文标题】:Spring Security keeps giving Error 404 GET /login [duplicate] 【发布时间】:2022-01-21 22:34:25 【问题描述】:

我已经设置了一个简单的 Spring Security 应用程序并启用了网络安全,但无法进入默认登录页面,它不断出现错误 404。如何解决这个问题?

这是我的配置。

application.properties

# database configs
spring.datasource.url=jdbc:h2:file:./testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
# Create Schema automatically
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.sql.init.mode=always
# Enabling H2 Console
spring.h2.console.enabled=true
# Custom H2 Console URL
spring.h2.console.path=/h2-console

##################################################

# session configs
spring.session.store-type=jdbc
spring.session.jdbc.table-name=SPRING_SESSION
spring.session.jdbc.initialize-schema=always
spring.session.timeout=86400

##################################################

debug=true

##################################################

# user configs
spring.security.user.name=user
spring.security.user.password=password

SecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter 

    private final IUserService userService;

    @Autowired
    public SecurityConfiguration(IUserService userService) 
        this.userService = userService;
    

    @Bean
    public PasswordEncoder getPasswordEncoder() 
        return new BCryptPasswordEncoder();
    

    @Bean
    public DaoAuthenticationProvider authProvider() 
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userService);
        authProvider.setPasswordEncoder(getPasswordEncoder());
        return authProvider;
    

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
        super.configure(auth);

        auth.authenticationProvider(authProvider());
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/h2-console/**").permitAll()
            .and()
            .formLogin().loginPage("/login").permitAll()
            .and()
            .logout().permitAll().logoutSuccessUrl("/")
            .and().csrf().ignoringAntMatchers("/h2-console/**") // needed to access the h2-console after introducing security module;
            .and().headers().frameOptions().sameOrigin() // needed to access the h2-console after introducing security module
            .and().logout().invalidateHttpSession(true).deleteCookies("JSESSIONID").logoutSuccessUrl("/login");
    

非常感谢您对出现问题的任何帮助。

编辑

[nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : GET "/login", parameters=
[nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler [classpath [META-INF/resources/], classpath [resources/], classpath [static/], classpath [public/], ServletContext [/]]
[nio-8080-exec-2] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
[nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed 404 NOT_FOUND
[nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/error", parameters=
[nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorhtml(HttpServletRequest, HttpServletResponse)
[nio-8080-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
[nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 404

编辑 2

plugins 
    id 'org.springframework.boot' version '2.6.1'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'


group = 'com.dsam'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations 
    compileOnly 
        extendsFrom annotationProcessor
    


repositories 
    mavenCentral()


dependencies 
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.session:spring-session-core'
    implementation 'org.springframework.session:spring-session-jdbc'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-validation'    // added manually
    implementation 'com.h2database:h2'  // added manually
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'


test 
    useJUnitPlatform()

【问题讨论】:

404 for /login/error?? ;) @xerx593 404 for /login @xerx593 我已经添加了错误日志。是因为 /error 页面吗? @EleftheriaStein-Kousathana 非常感谢。有效。这解决了问题。 【参考方案1】:

spring-security 自动配置/login 页面(“视图和控制器”),但如果我们希望它工作/服务,我们不得

.loginPage(...)

..否则我们负责(呈现视图)。

来自(优秀)javadoc:

登录页面:

如果需要登录,则指定将用户发送到的 URL。如果与 WebSecurityConfigurerAdapter 一起使用,则当此属性未指定时,将生成默认登录页面。 ...

【讨论】:

以上是关于Spring Security 不断给出错误 404 GET /login [重复]的主要内容,如果未能解决你的问题,请参考以下文章

Spring security hasRole() 给出错误 403 - 访问被拒绝

带有自定义 AuthenticationProvider 的 spring security 给出了拒绝访问错误

Spring安全性j_spring_security_check调用给出404未找到错误[关闭]

spring security 在重定向到 logout.jsp 时给出错误

Pdf下载使用java jersey和spring security在给出邮递员的请求时给出错误

Angular 的 Spring Boot 授权服务器访问 - 不断给出 CORS 错误