gpt4 book ai didi

java - 如何向 HttpSecurity 添加自定义过滤器并检索用户? ( Spring 安全)

转载 作者:行者123 更新时间:2023-11-29 04:18:22 29 4
gpt4 key购买 nike

WebSecurityConfigurerAdapter 类中,我们使用 protected void configure(HttpSecurity http) 方法为请求添加限制。我想要的是:

1.检索要进入的用户
2.检查该用户是否存在于数据库中
3.检查该用户是否有特殊属性,例如:login.endsWith('_login')

最佳答案

您只需实现自定义 AuthenticationProvider。根据需要由其他服务器执行验证码。

@Component
public class CustomAuthenticationProvider
implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {

String name = authentication.getName();
String password = authentication.getCredentials().toString();

if (shouldAuthenticateAgainstThirdPartySystem()) {

// use the credentials
// and authenticate against the third-party system
return new UsernamePasswordAuthenticationToken(
name, password, new ArrayList<>());
} else {
return null;
}
}

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

并注册您的身份验证提供程序。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private CustomAuthenticationProvider authProvider;

@Override
protected void configure(
AuthenticationManagerBuilder auth) throws Exception {

auth.authenticationProvider(authProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
}

Note : I am assuming you're using HTTP Basic Authentication, you can to change it to FormLogin or as per your need.

关于java - 如何向 HttpSecurity 添加自定义过滤器并检索用户? ( Spring 安全),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870048/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com