Spring Security总是将我重定向到默认的登录页面。

huangapple go评论81阅读模式
英文:

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(&quot;/**&quot;).allowedOrigins(&quot;*&quot;).allowedMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;OPTIONS&quot;, &quot;PUT&quot;)
.allowedHeaders(&quot;Content-Type&quot;, &quot;X-Requested-With&quot;, &quot;accept&quot;, &quot;Origin&quot;, &quot;Access-Control-Request-Method&quot;,
&quot;Access-Control-Request-Headers&quot;, &quot;Access-Control-Allow-Origin&quot;, &quot;Access-Control-Allow-Method&quot;, &quot;Set-Cookie&quot;)
.exposedHeaders(&quot;Access-Control-Allow-Origin&quot;, &quot;Access-Control-Allow-Credentials&quot;)
.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, &quot;/**&quot;).permitAll()
.antMatchers(&quot;/&quot;, &quot;index&quot;, &quot;/css/*&quot;, &quot;/js/*&quot;).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.loginProcessingUrl(&quot;/perform_login&quot;).permitAll()
.defaultSuccessUrl(&quot;/authenticated&quot;, true)
.usernameParameter(&quot;username&quot;)
.passwordParameter(&quot;password&quot;)
.failureUrl(&quot;/notauthenticated&quot;)
.and()
.logout()
.logoutUrl(&quot;/perform_logout&quot;)
.deleteCookies(&quot;JSESSIONID&quot;)
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}

The 2 Endpoints:

    @RequestMapping(value = &quot;/authenticated&quot;, method = RequestMethod.GET)
public ResponseEntity&lt;Boolean&gt; authenticate(){
return new ResponseEntity&lt;&gt;(true, HttpStatus.OK);
}
@RequestMapping(value = &quot;/notauthenticated&quot;, method = RequestMethod.GET)
public ResponseEntity&lt;Boolean&gt; notAuthenticate(){
return new ResponseEntity&lt;&gt;(false, HttpStatus.OK);
}

The submit function in reactjs looks like this:

   handleSubmit = async e =&gt; {
e.preventDefault();
const { username, password } = this.state;
try {
let res = await Axios({
method: &#39;POST&#39;,
headers: {
&quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded;charset=UTF-8&quot;
},
url: &quot;/perform_login&quot;,
data: &quot;username=&quot; + username + &quot;&amp;password=&quot; + password
});
let redirectUrl = await res.request.responseURL;
console.log(res);
console.log(redirectUrl);
if(redirectUrl !== &#39;http://localhost:8080/notauthenticated&#39;){
}
} 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( { &quot;it.myapplication.controllers&quot; } )
@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( &quot;/&quot;,&quot;/home&quot;) 
.permitAll() 
.anyRequest()
.authenticated().and()
.formLogin().loginPage( &quot;/login&quot; )
.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.

 &lt;body&gt;
&lt;div th:if=&quot;${param.error}&quot;&gt;
Invalid username and password.
&lt;/div&gt;
&lt;div th:if=&quot;${param.logout}&quot;&gt;
You have been logged out.
&lt;/div&gt;
&lt;form th:action=&quot;@{/login}&quot; method=&quot;post&quot;&gt;
&lt;div&gt;&lt;label&gt; User Name : &lt;input type=&quot;text&quot; name=&quot;username&quot;/&gt; &lt;/label&gt;&lt;/div&gt;
&lt;div&gt;&lt;label&gt; Password: &lt;input type=&quot;password&quot; name=&quot;password&quot;/&gt; &lt;/label&gt;&lt;/div&gt;
&lt;div&gt;&lt;input type=&quot;submit&quot; value=&quot;Sign In&quot;/&gt;&lt;/div&gt;
&lt;/form&gt;
&lt;/body&gt;

I hope this can help you.

huangapple
  • 本文由 发表于 2020年1月7日 00:03:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615260.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定