簡體   English   中英

我可以在Spring Security中進行身份驗證嗎?

[英]I am able to make authentication in Spring Security?

我正在使用Spring Security根據角色對用戶進行身份驗證。 /**身份驗證可以得到:

頁面加載失敗,並顯示錯誤:HTTP重定向過多

錯誤和登錄頁面未顯示。

  protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
            .antMatchers("/login*").authenticated()
            .antMatchers("/**").authenticated()
            .and()
            .formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/welcome")
            .usernameParameter("username").passwordParameter("password")
            .and()
            .logout().logoutSuccessUrl("/login?logout").logoutUrl("/login?logout")
            .and()
            .exceptionHandling().accessDeniedPage("/accessDenied")
            .and()
            .csrf();
        }

但是,如果我這樣做:

protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/login").authenticated()
        .antMatchers("/").authenticated()
        .and()
        .formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/welcome")
        .usernameParameter("username").passwordParameter("password")
        .and()
        .logout().logoutSuccessUrl("/login?logout").logoutUrl("/login?logout")
        .and()
        .exceptionHandling().accessDeniedPage("/accessDenied")
        .and()
        .csrf();
    }

此代碼對/** URL進行身份驗證有什么問題?

未經身份驗證的用戶無法訪問您的登錄頁面:

 .antMatchers("/login*").authenticated() 

因此,Spring Security重定向到您的登錄頁面,該頁面也重定向到您的登錄頁面,...

您必須允許未經身份驗證的用戶訪問您的登錄頁面,請參閱Spring Security Reference

雖然自動生成的登錄頁面便於快速啟動和運行,但是大多數應用程序都希望提供自己的登錄頁面。 為此,我們可以如下所示更新配置:

 protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") 1 .permitAll(); 2 } 

1更新的配置指定登錄頁面的位置。

2我們必須授予所有用戶(即未經身份驗證的用戶)訪問我們登錄頁面的權限。 formLogin().permitAll()方法允許向所有用戶授予與基於表單的登錄相關聯的所有URL的訪問權限。

如果刪除通配符( * ),則未經login驗證的用戶可以訪問所有頁面, login/除外。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM