英文:
Spring Security always redirecting me to the default login page
问题
以下是您要翻译的内容:
Issue
我正在使用Spring Boot作为后端,React JS作为前端。我的问题是,如果身份验证成功,我总是被重定向到http://localhost:8080/login
。这是默认的登录页面。在我的安全类中,我已经配置了如果身份验证成功,它将重定向到http://localhost:8080/authenticated
,如果失败,则重定向到http://localhost:8080/notauthenticated
。如果我输入错误的用户名和密码,它可以正常工作。它会重定向我到http://localhost:8080/notauthenticated
,但如果我输入正确的用户名和密码,它总是重定向我到http://localhost:8080/login
,但我会得到一个有效的会话ID。如果我输入错误的凭据,我也会得到一个会话ID,但这个会话ID不起作用,这是有道理的。
/authenticated
和/notauthenticated
只是两个端点,它们只返回一个带有布尔类型的ResponseEntity。
我也不明白为什么它不返回true或false。在Postman中,如果我已经经过身份验证,我会得到true,但如果没有经过身份验证,它会将我重定向到默认的登录页面。
Code
Spring Security配置类:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers", "Access-Control-Allow-Origin", "Access-Control-Allow-Method", "Set-Cookie")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
.allowCredentials(true).maxAge(3600);
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Autowired
UserDetailsServiceImpl userDetailsService;
@Bean
DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
return daoAuthenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/", "index", "/css/*", "/js/*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.loginProcessingUrl("/perform_login").permitAll()
.defaultSuccessUrl("/authenticated", true)
.usernameParameter("username")
.passwordParameter("password")
.failureUrl("/notauthenticated")
.and()
.logout()
.logoutUrl("/perform_logout")
.deleteCookies("JSESSIONID")
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
这两个端点:
@RequestMapping(value = "/authenticated", method = RequestMethod.GET)
public ResponseEntity<Boolean> authenticate(){
return new ResponseEntity<>(true, HttpStatus.OK);
}
@RequestMapping(value = "/notauthenticated", method = RequestMethod.GET)
public ResponseEntity<Boolean> notAuthenticate(){
return new ResponseEntity<>(false, HttpStatus.OK);
}
ReactJS中的提交函数如下:
handleSubmit = async e => {
e.preventDefault();
const { username, password } = this.state;
try {
let res = await Axios({
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
url: "/perform_login",
data: "username=" + username + "&password=" + password
});
let redirectUrl = await res.request.responseURL;
console.log(res);
console.log(redirectUrl);
if(redirectUrl !== 'http://localhost:8080/notauthenticated'){
}
} catch (err) {
console.log(err);
}
};
英文:
Issue
So I am using Spring boot as backend and React JS as frontend. My Issue is that I am always getting redirect to http://localhost:8080/login
if the authentication is successful. This is the default login page. In my security class I have configured that it will redirect to http://localhost:8080/authenticated
if authentication is successful and if it fails then redirect to http://localhost:8080/notauthenticated
. If I type wrong username and password it works. It redirects me to http://localhost:8080/notauthenticated
but if I type the correct username and password it always redirects me to http://localhost:8080/login
but I get a sessionid that works. If I type wrong credentials I also get a sessionid but this sessionid doesn't work which make sense.
/authenticated
and /notauthenticated
are just 2 Endpoints that just return a ResponseEntity with a type of Boolean.
I also don't understand why it doesn't return true or false. In postman I get true if I'm authenticated but if not then it redirects me to the default login page.
Code
Spring Security Config Class:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers", "Access-Control-Allow-Origin", "Access-Control-Allow-Method", "Set-Cookie")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
.allowCredentials(true).maxAge(3600);
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Autowired
UserDetailsServiceImpl userDetailsService;
@Bean
DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
return daoAuthenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/", "index", "/css/*", "/js/*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.loginProcessingUrl("/perform_login").permitAll()
.defaultSuccessUrl("/authenticated", true)
.usernameParameter("username")
.passwordParameter("password")
.failureUrl("/notauthenticated")
.and()
.logout()
.logoutUrl("/perform_logout")
.deleteCookies("JSESSIONID")
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
The 2 Endpoints:
@RequestMapping(value = "/authenticated", method = RequestMethod.GET)
public ResponseEntity<Boolean> authenticate(){
return new ResponseEntity<>(true, HttpStatus.OK);
}
@RequestMapping(value = "/notauthenticated", method = RequestMethod.GET)
public ResponseEntity<Boolean> notAuthenticate(){
return new ResponseEntity<>(false, HttpStatus.OK);
}
The submit function in reactjs looks like this:
handleSubmit = async e => {
e.preventDefault();
const { username, password } = this.state;
try {
let res = await Axios({
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
url: "/perform_login",
data: "username=" + username + "&password=" + password
});
let redirectUrl = await res.request.responseURL;
console.log(res);
console.log(redirectUrl);
if(redirectUrl !== 'http://localhost:8080/notauthenticated'){
}
} catch (err) {
console.log(err);
}
};
答案1
得分: 0
以下是您提供的内容的中文翻译:
我遇到了相同的问题,通过将以下注解添加到我的SpringWebApplication类中,我解决了这个问题,这会告诉Spring移除默认配置。
@ComponentScan( { "it.myapplication.controllers" } )
@EnableCaching
@SpringBootApplication( exclude = { SecurityAutoConfiguration.class } )
public class MyWebApplication{
public static void main( String[] args ){
SpringApplication.run( MyWebApplication.class, args );
}
}
在我的WebSecurityConfig类中,我没有改变任何东西。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http
.authorizeRequests()
.antMatchers( "/", "/home")
.permitAll()
.anyRequest()
.authenticated().and()
.formLogin().loginPage( "/login" )
.permitAll().and().logout().permitAll();
}
}
我创建了一个简单的login.html页面放在resources/templates下,其中包含登录表单。我使用thymeleaf作为模板引擎。
<body>
<div th:if="${param.error}">
无效的用户名和密码。
</div>
<div th:if="${param.logout}">
您已注销。
</div>
<form th:action="@{/login}" method="post">
<div><label> 用户名 : <input type="text" name="username"/> </label></div>
<div><label> 密码: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="登录"/></div>
</form>
</body>
希望这可以帮助您。
英文:
I was having the same problem and I solved by adding this annotation to my SpringWebApplication class, this specify to Spring to remove default configuration
@ComponentScan( { "it.myapplication.controllers" } )
@EnableCaching
@SpringBootApplication( exclude = { SecurityAutoConfiguration.class } )
public class MyWebApplication{
public static void main( String[] args ){
SpringApplication.run( MyWebApplication.class, args );
}
}
In my WebSecurityConfig class I didn't change nothing
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http
.authorizeRequests()
.antMatchers( "/","/home")
.permitAll()
.anyRequest()
.authenticated().and()
.formLogin().loginPage( "/login" )
.permitAll().and().logout().permitAll();
}
And I created a simple login.html page under resources/templates containing the login form. I'm using thymeleaf as template engine.
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
I hope this can help you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论