英文:
Spring Security is initializing but does not validate the login form data
问题
以下是翻译好的代码部分:
WebSecurityConfig.java
package com.XXX.brxm.security;
import org.springframework.beans.factory.annotation.Autowired;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ImplementsUserDetailsService userDetailsSevice;
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("HTTP SECURITY!!!");
http.csrf().disable()
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/img/**", "favicon.ico")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("Autenticação!!!");
auth.userDetailsService(userDetailsSevice).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/materialize/**", "/style/**", "/resources/**", "/favicon.ico", "/**");
}
}
ImplementsUserDetailsService.java
package com.XXX.brxm.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import com.XXX.brxm.login.model.Login;
import com.XXX.brxm.login.repository.LoginRepository;
@Repository
public class ImplementsUserDetailsService implements UserDetailsService {
@Autowired
private LoginRepository ur;
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
Login usuario = ur.findByLogin(login);
if(usuario == null)
throw new UsernameNotFoundException("User not found!");
return usuario;
}
}
LoginController.java
package com.XXX.brxm.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class LoginController {
@RequestMapping(value = "/login")
public String login() {
return "login";
}
}
Login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XXX</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
<meta charset="UTF-8">
</head>
<body>
<div class="login_main">
<div class="login-page">
<img src="/img/logo_grande_fundo_transparente.png" id="logo_form" />
<div th:fragment="content" class="form">
<center><strong><legend class="form_text_title">Autenticação</legend></strong></center>
<br>
<form name="f" th:action="@{/login}" method="POST" class="login-form">
<fieldset class="input_form_fieldset border_form">
<legend align="left" class="form_text"> Usuário </legend>
<input type="text" id="username" name="username" />
</fieldset>
<br>
<fieldset class="input_form_fieldset border_form">
<legend align="left" class="form_text"> Senha </legend>
<input type="password" id="password" name="password" />
</fieldset>
<div class="form-actions">
<button type="submit" class="btn border_form">Entrar</button>
</div>
</form>
<div th:if="${param.error}" class="error">Usuário ou Senha Inválidos.</div>
<div th:if="${param.logout}" class="alert alert-success">Sessão Encerrada.</div>
<br>
<center><p>Copyright © XXX 2020.</p></center>
</div>
</div>
</div>
<style>
@media (min-device-width: 700px) {
/* CSS 样式省略... */
}
</style>
<script>
$('.message a').click(function() {
$('form').animate({
height: "toggle",
opacity: "toggle"
}, "slow");
});
</script>
</body>
</html>
Main.java
package com.XXX.brxm;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.Arrays;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@EnableScheduling
@SpringBootApplication
@EnableResourceServer
public class Main {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job transmissionJob;
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Scheduled(cron = "0 */1 * * * ?")
public void perform() throws Exception {
JobParameters params = new JobParametersBuilder()
.addString("JobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();
jobLauncher.run(transmissionJob, params);
}
}
请注意,上述翻译可能会涉及到一些代码格式或标点符号的调整,以确保翻译后的代码能够正确运行。如果在实际应用中遇到问题,请逐行检查翻译是否正确。
英文:
I am trying to use Spring Security to authenticate on my Login screen, however any data I type it allows, even blank.
It looks like he's not even triggering the Spring Security module.
In the past this application worked, but the packages were different, after they reorganized the packages, it started to give this problem.
Another test I performed was to remove the code .loginPage ("/ login") and when accessing http: // localhost: 8080 / login error 400 is returned. In my opinion, if the Security module was being called it would return at least error 500, correct?
Can you help me ?
WebSecurityConfig.java
package com.XXX.brxm.security;
import org.springframework.beans.factory.annotation.Autowired;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ImplementsUserDetailsService userDetailsSevice;
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("HTTP SECURITY!!!");
http.csrf().disable()
.authorizeRequests()
.antMatchers("/css/**", "/js/**","/img/**", "favicon.ico")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("Autenticação!!!");
auth.userDetailsService(userDetailsSevice).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/materialize/**", "/style/**", "/resources/**", "/favicon.ico", "/**");
}
}
ImplementsUserDetailsService.java
package com.XXX.brxm.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import com.XXX.brxm.login.model.Login;
import com.XXX.brxm.login.repository.LoginRepository;
@Repository
public class ImplementsUserDetailsService implements UserDetailsService{
@Autowired
private LoginRepository ur;
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
Login usuario = ur.findByLogin(login);
if(usuario == null)
throw new UsernameNotFoundException("User not found!");
return usuario;
}
}
POM.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.XXX</groupId>
<artifactId>Publisher</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>publisher</name>
<description>Publisher module for XXX</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-infrastructure</artifactId>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId>
</dependency> -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<type>jar</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
LoginController.java
package com.XXX.brxm.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class LoginController {
@RequestMapping(value = "/login")
public String login() {
return "login";
}
}
Login.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XXX</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
<meta charset="UTF-8">
</head>
<body>
<div class="login_main">
<div class="login-page">
<img src="/img/logo_grande_fundo_transparente.png" id="logo_form" />
<div th:fragment="content" class="form">
<center><strong><legend class="form_text_title">Autenticação</legend></strong></center>
<br>
<form name="f" th:action="@{/login}" method="POST"
class="login-form">
<fieldset class="input_form_fieldset border_form">
<legend align="left" class="form_text"> Usuário </legend>
<input type="text" id="username" name="username" />
</fieldset>
<br>
<fieldset class="input_form_fieldset border_form">
<legend align="left" class="form_text"> Senha </legend>
<input type="password" id="password" name="password" />
</fieldset>
<div class="form-actions">
<button type="submit" class="btn border_form">Entrar</button>
</div>
</form>
<div th:if="${param.error}" class="error">Usuário ou Senha Inválidos.</div>
<div th:if="${param.logout}" class="alert alert-success">Sessão Encerrada.</div>
<br>
<center><p>Copyright &copy; XXX 2020.</p></center>
</div>
</div>
</div>
<style>
@media ( min-device-width : 700px) {
.form_text_title{
color: #01143d;
font-weight: 800;
font-size: 20px;
}
.form_text{
color: #35363a;
font-weight: 800;
font-size: 12px;
}
.error{
color: red;
}
.border_form{
border-radius: 4px;
}
.login_main {
margin: 2% 28%;
}
.form-actions {
padding-top: 10%;
}
.input_form_fieldset {
border-color: #35363a;
padding-inline-start: 1%;
padding-inline-end: 1%;
padding-bottom: 0%;
}
#logo_form {
margin-left: 12%;
width: 250px;
padding-bottom: 14%;
}
.login-page {
width: 360px;
padding: 8% 0 0;
margin: auto;
}
.form {
z-index: 1;
background: #43a04700;
max-width: 360px;
margin: 0 auto 100px;
padding: 45px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0
rgba(0, 0, 0, 0.24);
}
.form input {
font-family: "Roboto", sans-serif;
outline: 0;
background: #0365a700;
width: 100%;
border: 0;
box-sizing: border-box;
font-size: 14px;
}
::-webkit-input-placeholder {
color: black;
}
.form button {
font-family: "Roboto", sans-serif;
text-transform: uppercase;
outline: 0;
background: #02123e;
width: 100%;
border: 0;
padding: 9px;
color: #FFFFFF;
font-size: 14px;
-webkit-transition: all 0.3 ease;
transition: all 0.3 ease;
cursor: pointer;
}
.form button:hover, .form button:active, .form button:focus {
background: #43A047;
}
.form .message {
margin: 15px 0 0;
color: #b3b3b3;
font-size: 12px;
}
.form .message a {
color: #4CAF50;
text-decoration: none;
}
.form .register-form {
display: none;
}
.container {
position: relative;
z-index: 1;
max-width: 300px;
margin: 0 auto;
}
.container:before, .container:after {
content: "";
display: block;
clear: both;
}
.container .info {
margin: 50px auto;
text-align: center;
}
.container .info h1 {
margin: 0 0 15px;
padding: 0;
font-size: 36px;
font-weight: 300;
color: #1a1a1a;
}
.container .info span {
color: #4d4d4d;
font-size: 12px;
}
.container .info span a {
color: #000000;
text-decoration: none;
}
.container .info span .fa {
color: #EF3B3A;
}
body {
font-family: "Roboto", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
}
</style>
<script>
$('.message a').click(function() {
$('form').animate({
height : "toggle",
opacity : "toggle"
}, "slow");
});
</script>
</body>
</html>
Main.java
package com.XXX.brxm;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.Arrays;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@EnableScheduling
@SpringBootApplication
@EnableResourceServer
public class Main {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job transmissionJob;
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Scheduled(cron = "0 */1 * * * ?")
public void perform() throws Exception {
JobParameters params = new JobParametersBuilder()
.addString("JobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();
jobLauncher.run(transmissionJob, params);
}
}
答案1
得分: 1
只需移除 @EnableResourceServer,我不明白你为什么需要它。
英文:
Just remove @EnableResourceServer, I don't see why you need it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论