首页 > 解决方案 > 添加凭据以访问 REST 控制器

问题描述

我有一个带有多个控制器的 Web 服务。我只需要为其中一个添加身份验证。其余的应该保持没有身份验证。请注意,我只需要在请求标头中添加用户名和密码。没有登录表格。我正在使用弹簧启动应用程序。

我试过的代码:

@Configuration
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

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

    auth.inMemoryAuthentication()
            .withUser("user").password("{noop}pass").roles("ADMIN");

}

// Secure the endpoints with HTTP Basic authentication
@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            //HTTP Basic authentication
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/myController").hasRole("ADMIN")
            .and()
            .csrf().disable()
            .formLogin().disable();
}

但是,它不要求用户和密码。如果我删除 {noop} 它会但会抛出无效密码编码器的异常

标签: javarestspring-boot

解决方案


我最终使用以下代码解决了我的问题:

@Configuration 公共类 ApplicationSecurityConfig 扩展 WebSecurityConfigurerAdapter {

public static String ROLE_NAME = "ROLENAME";

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

    auth.inMemoryAuthentication().passwordEncoder(new Pbkdf2PasswordEncoder("key", 10000, 128))
            .withUser("userName").password("encryptedPassword").roles(ROLE_NAME);

}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/securedPath").hasRole(ROLE_NAME)
            .and()
            .csrf().disable()
            .formLogin().disable();
}

}

您可以配置加密密码并对此代码应用所需的任何更改。主要目标是只保护一个带有路径securedPath的其余API,给定的用户名和密码可以在加密或不加密的情况下使用。在我的示例中,我使用了加密密码并将其添加到配置文件中。这个类会自动解密密码并使用它。无需 UI,因为浏览器会自动弹出登录表单。


推荐阅读