簡體   English   中英

使用自定義身份驗證提供程序在 Spring Security 中接受無效密碼

[英]Invalid password is accepted in spring security using custom Authentication Provider

我正在使用基本身份驗證與自定義身份驗證提供程序一起使用 spring 安全性。

當我嘗試通過郵遞員調用后端 API GET 時,只有當我更改用戶名時它才能正常工作

這是問題陳述 - 每當我修改用戶名時,只有自定義身份驗證器提供程序有效。 一旦我添加了正確的用戶名和密碼,它就可以工作了,但是在那之后,當我對密碼進行任何更改(給出錯誤的密碼)時,總是顯示 200 成功響應。 如果我正在更改用戶名(提供錯誤的用戶名),則只會調用自定義身份驗證器提供程序並獲得 401 響應。

Java Spring 代碼

@Configuration
@EnableWebSecurity
@ComponentScan("com.authentication.service")
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{     

    @Autowired
    private AuthService authProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception { http
         .httpBasic().and().logout().clearAuthentication(true).and() .authorizeRequests()
         .antMatchers("/index.html", "/", "/home", "/login", "/assets/**").permitAll()
         .anyRequest().authenticated() .and() .csrf()
         .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); }

}

@Service
public class AuthService implements AuthenticationProvider{

@Override
    public Authentication authenticate(Authentication authentication)
            throws org.springframework.security.core.AuthenticationException {
        String userName = (String) authentication.getPrincipal();
        String userPassword = authentication.getCredentials().toString();
        
        if(authenticateUser(userName, userPassword)) {
            return new UsernamePasswordAuthenticationToken(userName, userPassword, new ArrayList<>());
        } else {
            return null;
        }
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

    public Boolean authenticateUser(String userName, String userPassword) {
        // Using some third party service
        // return true if user is authenticated else false
     }
}

郵差

發生這種情況是因為 Spring Security 正在創建一個會話,該會話在身份驗證成功后作為 Cookie 返回(您可以在 Postman 響應中的 Cookies 面板中進行檢查)。 對於進一步的請求,即使您提供了無效的憑據,Postman 也會發送此會話 cookie,該 cookie 將用於身份驗證。

要消除這種影響,您可以將會話管理策略更新為SessionCreationPolicy.STATELESS ,這將確保應用程序不會創建會話,並且請求中發送的Basic Auth身份Basic Auth憑據用於身份驗證。

您可以像這樣更新會話管理策略:

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{     
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

暫無
暫無

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

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