簡體   English   中英

使用UserDetailsS​​ervice和Java配置登錄Spring Security

[英]Spring Security login with UserDetailsService and Java config

我正在嘗試使用Spring Security在數據庫查找中添加登錄功能,而我真的很努力。 我想通過實現UserDetailsService接口來查找用戶。 我已經閱讀了大量的文檔,並用Google搜索了幾個小時,但是我仍然陷於困境。 我可以找到的大多數示例都使用XML,所以也許我的問題與將其轉換為Java配置有關。

的UserDetailsS​​ervice

@Service
public class AccountServiceImpl implements AccountService { // AccountService implements UserDetailsService
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        // The email variable is always ''

        List<GrantedAuthority> authList = new ArrayList<>();
        authList.add(new Role("ROLE_USER")); // Role implements GrantedAuthority

        return new User("test@example.com", "password", true, true, true, true, authList);
    }
}

安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private AccountService accountService;


    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        // This bean is required for using method security annotations
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login/process")
                .failureUrl("/login?error=true")
                .defaultSuccessUrl("/", false)
                .and()
                //.userDetailsService(this.accountService)
                .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessHandler(this.logoutSuccessHandler)
                    .invalidateHttpSession(true)
                .and()
                // Permissions here
                .csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("test@example.com").password("password").roles("USER");
    }

    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                //.userDetailsService(this.accountService);
                .inMemoryAuthentication()
                .withUser("test@example.com").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }*/

    /*@Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(this.accountService);
        return provider;
    }*/
}

如您所見,有一堆過時的代碼,這些只是我試圖使其工作的一部分。 我還嘗試了簡單的內存身份驗證,但是那也不起作用。

login.jsp的

<form action="/login/process" method="POST">
    <input name="j_username" id="j_username" type="text" />
    <input name="j_password" id="j_password" type="password" />

    <input type="submit" value="Login" />
</form>

調試

DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Request is to process authentication

DEBUG org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider

DEBUG org.springframework.security.authentication.dao.DaoAuthenticationProvider - User '' not found

DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials

DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Updated SecurityContextHolder to contain null Authentication

對於我嘗試過的所有配置,上述情況似乎總是如此。 我什至不確定為什么要使用DaoAuthenticationProvider ,即使我嘗試覆蓋它也是如此。 我想這是默認值。 對於上述某些配置,將調用我的UserDetailsService實現,但參數為空字符串。 同樣,即使我返回了一個硬編碼的UserDetails對象,其憑據與在表單中輸入的憑據相同,身份驗證仍然失敗,並且我被重定向回/login?error=true

我在這里做錯了什么? 請告知我我的錯誤,或提供一個使用Java配置的簡單示例。 謝謝!

在基於Java的配置中使用Spring Security時,請求參數的名稱是usernamepassword而不再是j_usernamej_password

您可以修改您的登錄表單

<form action="/login/process" method="POST">
    <input name="username" id="j_username" type="text" />
    <input name="password" id="j_password" type="password" />

    <input type="submit" value="Login" />
</form>

或修改您的配置以使用舊的字段名稱。

formLogin().usernameParameter("j_username").passwordParameter("j_password");

兩種方法都可以解決您的問題。

暫無
暫無

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

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