【发布时间】:2023-01-12 02:28:37
【问题描述】:
当我添加我的 websecurityconfig 文件时,我收到 404 错误。我的 Websecurityconfig 如下所示。令人恼火的是这在本地有效,但在部署时却无效。我试图点击我的应用程序的头部,我希望它重定向到登录页面,但在登录之前它是 404
package org.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.example.demo.LoginSuccessHandler;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/abc").hasAnyAuthority("ROLE_one")
.antMatchers("/def").hasAnyAuthority("ROLE_one")
.antMatchers("/ghi").hasAnyAuthority("ROLE_one")
.antMatchers("/jkl").hasAnyAuthority("ROLE_one")
.antMatchers("/mno").hasAnyAuthority("ROLE_one")
.antMatchers("/pqr").hasAnyAuthority("ROLE_one")
.antMatchers("/stu").hasAnyAuthority("ROLE_two")
.antMatchers("/vwx").hasAnyAuthority( "ROLE_two")
.antMatchers("/yza").hasAnyAuthority("ROLE_two")
.antMatchers("/bcd").hasAnyAuthority("ROLE_two")
.antMatchers("/").permitAll()
.and().formLogin()
.successHandler(successHandler)
.and().logout().permitAll();
}
@Autowired private LoginSuccessHandler successHandler;
}
我尝试删除它以消除 404 错误,但我需要设置安全性。
【问题讨论】:
标签: spring spring-boot spring-mvc spring-security spring-data-jpa