为 Rest Api 实施 Spring Security

Pet*_*zov 3 spring spring-security spring-boot

我使用此代码进行 Rest API 身份验证:

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Optional<String> basicToken = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION))
                .filter(v -> v.startsWith("Basic"))
                .map(v -> v.split("\\s+")).filter(a -> a.length == 2).map(a -> a[1]);
        if (!basicToken.isPresent()) {
            return sendAuthError(response);
        }

        byte[] bytes = Base64Utils.decodeFromString(basicToken.get());
        String namePassword = new String(bytes, StandardCharsets.UTF_8);
        int i = namePassword.indexOf(':');
        if (i < 0) {
            return sendAuthError(response);
        }
        String name = namePassword.substring(0, i);
        String password = namePassword.substring(i + 1);
//        Optional<String> clientId = authenticationService.authenticate(name, password, request.getRemoteAddr());
        Merchants merchant = authenticationService.authenticateMerchant(name, password, request.getRemoteAddr());
        if (merchant == null) {
            return sendAuthError(response);
        }
        request.setAttribute(CURRENT_CLIENT_ID_ATTRIBUTE, merchant.getId());
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

我如何使用 Spring Security 重写代码以获得相同的结果,但对不同的链接进行身份验证?例如:

localhost:8080/v1/notification - requests should NOT be authenticated.
localhost:8080/v1/request - requests should be authenticated.
Run Code Online (Sandbox Code Playgroud)

Ang*_*ata 6

在这里您可以找到一个工作项目https://github.com/angeloimm/springbasicauth

我知道 pom.xml 文件中有很多无用的依赖项,但我从一个已经存在的项目开始,我没有时间净化它

基本上你必须:

  • 配置弹簧安全
  • 配置 spring mvc
  • 根据 spring security 实现您自己的身份验证提供程序。注意我使用了 inMemoryAuthentication。请根据自己的意愿修改

让我解释一下代码。

Spring MVC 配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"it.olegna.test.basic"})
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter());
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,除了通过告诉 Spring MVC 在哪里找到控制器等以及使用单个消息转换器来配置 Spring MVC 之外,我们没有做任何其他事情;为了MappingJackson2HttpMessageConverter生成 JSON 响应

春季安全配置

@Configuration
@EnableWebSecurity
@Import(value= {WebMvcConfig.class})
public class WebSecConfig extends WebSecurityConfigurerAdapter {
     @Autowired private RestAuthEntryPoint authenticationEntryPoint;

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth
              .inMemoryAuthentication()
              .withUser("test")
              .password(passwordEncoder().encode("testpwd"))
              .authorities("ROLE_USER");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
              .authorizeRequests()
              .antMatchers("/securityNone")
              .permitAll()
              .anyRequest()
              .authenticated()
              .and()
              .httpBasic()
              .authenticationEntryPoint(authenticationEntryPoint);
        }
        @Bean
        public PasswordEncoder passwordEncoder() {
            return NoOpPasswordEncoder.getInstance();
        }
}
Run Code Online (Sandbox Code Playgroud)

这里我们配置 Spring Security,以便对除以 securityNone 开头的请求之外的所有请求使用 HTTP 基本身份验证。我们使用 aNoOpPasswordEncoder来对提供的密码进行编码;这个 PasswrodEncoder 绝对不做任何事情......它让密码保持原样。

休息入口点

@Component
public class RestAuthEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,  AuthenticationException authException) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}
Run Code Online (Sandbox Code Playgroud)

此入口点禁用所有不包含身份验证标头的请求

SimpleDto:一个非常简单的 DTO,表示来自控制器的 JSON 答案

public class SimpleDto implements Serializable {

    private static final long serialVersionUID = 1616554176392794288L;
    private String simpleDtoName;

    public SimpleDto() {
        super();
    }
    public SimpleDto(String simpleDtoName) {
        super();
        this.simpleDtoName = simpleDtoName;
    }
    public String getSimpleDtoName() {
        return simpleDtoName;
    }
    public void setSimpleDtoName(String simpleDtoName) {
        this.simpleDtoName = simpleDtoName;
    }

}
Run Code Online (Sandbox Code Playgroud)

TestBasicController:一个非常简单的控制器

@RestController
@RequestMapping(value= {"/rest"})
public class TestBasicController {
    @RequestMapping(value= {"/simple"}, method= {RequestMethod.GET}, produces= {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<List<SimpleDto>> getSimpleAnswer()
    {
        List<SimpleDto> payload = new ArrayList<>();
        for(int i= 0; i < 5; i++)
        {
            payload.add(new SimpleDto(UUID.randomUUID().toString()));
        }
        return ResponseEntity.ok().body(payload);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您使用邮递员或任何其他测试器尝试此项目,您可能会遇到两种情况:

  • 需要身份验证
  • 一切都好

假设您想要调用 URL http://localhost:8080/test_basic/rest/simple而不传递 Authentication 标头。HTTP 状态代码将是401 Unauthorized

这意味着需要身份验证标头

通过将此标头添加到请求中,Authorization Basic dGVzdDp0ZXN0cHdk一切都很好。请注意,StringdGVzdDp0ZXN0cHdk是字符串的 Base64 编码username:passwordtest:testpwd在我们的例子中是inMemoryAuthentication 中定义的 Base64 编码

我希望这有用

安吉洛

网络安全用户数据服务

为了配置 Spring security 从数据库检索用户详细信息,您必须执行以下操作:

创建一个 org.springframework.security.core.userdetails.UserDetailsS​​ervice 实现,如下所示:

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private BasicService svc;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BasicUser result = svc.findByUsername(username);
        if( result == null )
        {
            throw new UsernameNotFoundException("No user found with username "+username);
        }
        return result;
    }

}
Run Code Online (Sandbox Code Playgroud)

将其注入到 spring security 配置中并像这样使用它:

public class WebSecConfig extends WebSecurityConfigurerAdapter {
    @Autowired private RestAuthEntryPoint authenticationEntryPoint;
    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//      auth
//      .inMemoryAuthentication()
//      .withUser("test")
//      .password(passwordEncoder().encode("testpwd"))
//      .authorities("ROLE_USER");
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
        .antMatchers("/securityNone")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .httpBasic()
        .authenticationEntryPoint(authenticationEntryPoint);
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
Run Code Online (Sandbox Code Playgroud)

我将代码推送到我提供的 github 链接上。在那里您可以找到基于以下内容的完整工作示例:

  • 春天 5
  • 春季安全5
  • 休眠
  • h2数据库

请随意调整以适应您自己的场景