gpt4 book ai didi

java - Spring 安全: Page does not redirect after login

转载 作者:行者123 更新时间:2023-12-01 19:27:20 26 4
gpt4 key购买 nike

我使用 Spring boot 和 Java 从头开始​​构建了一个 Web 应用程序。现在我想将Spring Security集成到系统中。

但是,我在使用 Spring Security 登录时遇到问题。我使用了自定义登录页面并且配置正确。不确定我错过了什么。

主要

@SpringBootApplication
@ComponentScan(basePackages = {"com.security"}, basePackageClasses = {LoginController.class})
@EntityScan(basePackages = {"com.auth"})
@EnableJpaRepositories(basePackages = {"com.auth.repository"})
public class CpexProjectApplication {

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

}

Controller

@Controller
public class LoginController {

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String getLogin() {
return "login";
}

}

安全配置

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private CustomUserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(getPasswordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/css/**","/scss/**","/vendor/**","/img/**","/js/**").permitAll()
.antMatchers(HttpMethod.POST, "/home/**").hasRole("ADMIN")
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home/**")
.permitAll();
}

private PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}

@Override
public boolean matches(CharSequence charSequence, String s) {
return true;
}
};
}

}

UserDetails 的自定义类

@SuppressWarnings("serial")
public class CustomUserDetails extends User implements UserDetails {

public CustomUserDetails(final User user) {
super(user);
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
.collect(Collectors.toList());
}

@Override
public String getPassword() {
return super.getPassword();
}

@Override
public String getUsername() {
return super.getName();
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}

}

application.properties

#CPEX database - UAT
spring.datasource.url=jdbc:sqlserver://10.100.2.254;databaseName=ROOT
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto=update

#View Resolver
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

#Bean Override
spring.main.allow-bean-definition-overriding=true

#For detailed logging during dev
logging.level.org.springframework=DEBUG

#Tomcat default port
server.port=8888

登录页面

<!DOCTYPE html>
<html lang="en">

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">

<title>CPEX - Login</title>

<!-- Custom fonts for this template-->
<link type="text/css" href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

<!-- Custom styles for this template-->
<link href="css/sb-admin-2.min.css" rel="stylesheet">

</head>

<body class="bg-gradient-primary">

<div class="container">

<!-- Outer Row -->
<div class="row justify-content-center">

<div class="col-xl-10 col-lg-12 col-md-9">

<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg-6 d-none d-lg-block bg-login-image border-right border-3">
<img class="img-responsive" src="img/sbc-logo.png" alt="">
<div id="loginSuccessAlert" class="alert alert-success" style="display: none;">
<strong>Login Successful!</strong>
</div>
<div id="loginDangerAlert" class="alert alert-danger" style="display: none;">
<strong>Please check your credentials.</strong>
</div>
</div>
<div class="col-lg-6">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4 display-4">CP Exchange</h1>
</div>
<form id="loginForm" class="user" action="home" method="POST">
<div class="form-group">
<input type="text" class="form-control form-control-user" id="name" name="name" placeholder="Enter Username...">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-user" id="password" name="password" placeholder="Password">
</div>
<input class="btn btn-primary btn-user btn-block" type="submit" value="Login" />
<hr>
</form>
<div class="text-center">
<a class="small" href="#">Forgot Password?</a>
</div>
</div>
</div>
</div>
</div>
</div>

</div>

</div>

  <!-- Bootstrap core JavaScript-->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>

<!-- Custom scripts for all pages-->
<script src="js/sb-admin-2.min.js"></script>
<!-- <script src="js/custom/validateLogin.js"></script> -->

</body>

</html>

首页

code is too long

自定义用户详细信息服务

@Service
public class CustomUserDetailsService implements UserDetailsService {

@Autowired
private UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
Optional<User> optionalUsers = userRepository.findByName(name);

optionalUsers
.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
return optionalUsers
.map(CustomUserDetails::new).get();
}
}

TIA

最佳答案

刚刚注意到您的登录 JSP 提交将触发您已配置为 defaultSuccessUrl/home,并且由于您尚未登录,它将返回登录页面。

请更改您的 login.jsp 中的以下行

<form id="loginForm" class="user" action="home" method="POST">

<form id="loginForm" class="user" action="perform_login" method="POST">

您也可以删除此行

.antMatchers(HttpMethod.POST, "/home/**").hasRole("ADMIN")

并添加

.loginProcessingUrl("/perform_login")

从配置方法现在只是尝试一下。

如果有效,请继续一一添加其他配置。

http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/css/**","/scss/**","/vendor/**","/img/**","/js/**").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/perform_login") // add Login submit url
.defaultSuccessUrl("/home/**")
.permitAll();

编辑1:

如果您使用inMemoryAuthentication,请添加userDetailsS​​ervice,如下所示

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.inMemoryAuthentication().passwordEncoder(getPasswordEncoder())
.withUser("admin").password("aaa11111").roles("ADMIN").and()
.withUser("user").password("bbb22222").roles("USER");

auth.userDetailsService(userDetailsService);
}

关于java - Spring 安全: Page does not redirect after login,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59297566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com