代码之家  ›  专栏  ›  技术社区  ›  orirab

在特定路径中使用用户名/密码身份验证

  •  0
  • orirab  · 技术社区  · 7 年前

    我有一个配置了工作安全性的spring项目,我正在尝试设置一个特定的路径,该路径将只接受基本用户/密码身份验证的REST调用,这可以是硬编码的。

    安全代码类似于:

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
            ...
            .and()
                .authorizeRequests()
                .antMatchers("my-path/**").authenticated()
        }
    

    我真的不明白spring是如何发挥所有魔力的,但我希望它看起来像:

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
            ...
            .and()
                .authorizeRequests()
                .antMatchers("my-path/**").authenticatedWithUserPassword("user", "pswd")
        }
    

    必须发生的两件事:

    • 我希望此路径仅适用于此用户/pswd,不适用于其他身份验证类型!
    0 回复  |  直到 7 年前
        1
  •  0
  •   orirab    7 年前

    this answer )但它解决了我的问题。

    首先,我创造了这个 AuthenticationProvider :

    public class ClusterInternalAuthenticationProvider implements AuthenticationProvider {
    
        public static final String USER = "...";
        public static final String PASSWORD = "...";
    
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken)authentication;
    
            Object principal = token.getPrincipal();
            Object credentials = token.getCredentials();
    
            if (principal.equals(USER) && credentials.equals(PASSWORD)) {
                return new UsernamePasswordAuthenticationToken(
                    principal,
                    credentials,
                    Collections.singletonList(new SimpleGrantedAuthority("RELEVANT_AUTHORITY"))
                );
            }
    
            throw new BadCredentialsException("Sorry mate, wrong credentials...");
        }
    
        @Override
        public boolean supports(Class<?> authentication) {
            return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
        }
    }
    
    

    这将尝试user/pswd组合,如果为true,则返回具有访问特定路径所需权限的凭据。

    接下来,在SecurityConfiguration中,我启用 httpBasic 加上我的 身份验证提供者 :

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
            ...
            .and()
                .authorizeRequests()
                .antMatchers("my-path/**").hasAuthority("RELEVANT_AUTHORITY")
            .and()
                .httpBasic()
            .and()
                .authenticationProvider(new ClusterInternalAuthenticationProvider());
        }