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

标签 java spring spring-security

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/

相关文章:

java - 为什么在authenticate(..)上返回的Authentication对象仍然需要包含凭据?

grails - 在 Grails Spring 应用程序中获取 LDAP 属性 memberof

spring-boot - 如何实现多后端服务、解耦架构的SSO

java - JSOUP 解析 XYZ.tor2web.org

java - 在 Eclipse 中从 sqlite 数据库加载 JAVA GUI 中的表时,如何添加表标题?

java - POST 到 Spring MVC Controller 结果为 "HttpMessageNotReadableException: Could not read JSON: No suitable constructor found"

java - 使用 HibernateTemplate 的 findByNamedParam 函数进行分页

java - 如何遍历我的链表来搜索和删除特定的字符串?

java - 通过局域网调用其他java应用程序的方法

java - 如何使用参数在触发器中设置模式?