【问题标题】:Multiple security configurations for specific endpoints特定端点的多种安全配置
【发布时间】:2020-02-23 01:02:55
【问题描述】:

我想知道是否有办法提供两种不同类型的身份验证? 用户应使用基本身份验证登录、注册、获取端点/login/register/user 的用户数据。当我调用 /api 时,它只能使用标头中提供的 JWT 令牌进行身份验证。

但是当我打电话给/api 时,我会在没有任何身份验证的情况下获得所有数据。当用户登录并调用/user 时,API 让 JWT 访问/api

我的代码:

基本认证配置:

@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors()
                .and()
            .csrf().disable();
        http
            .authorizeRequests()
                .antMatchers("/user").authenticated()
                .antMatchers("/register").permitAll()
                .and()
            .formLogin().permitAll()
                .defaultSuccessUrl("/user");
    }

JWT 身份验证配置:

@Configuration
@Order(2)
public class JWTSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .antMatcher("/api/**")
            .addFilterAfter(new JWTAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic().disable();
    }

【问题讨论】:

标签: java spring spring-security


【解决方案1】:

我有同样的问题,我想要一些端点的基本身份验证,而其他一些我想要其他身份验证方法。像你的。你想要一些端点的基本身份验证(/login/register/user)和其他一些端点的 JWT 身份验证(/api/**)。

我使用了一些关于多个entry points in spring security的教程但是没有用。

所以这是我的解决方案(有效)

通过创建自定义过滤器将基本身份验证JWT身份验证分开。

  1. 为应使用基本身份验证进行身份验证的端点添加前缀路径。喜欢 : (/basic/login,/basic/register,/basic/user)

  2. /basic 前缀(用于/basic 请求)创建一个新的自定义过滤器并检查基本身份验证

    @Component
    public class BasicAuthenticationFilter implements Filter {
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    
        //Check for the requests that starts with /basic 
        if (httpServletRequest.getRequestURI().startsWith("/basic/")) {
    
            try {
                //Fetch Credential from authorization header
                String authorization = httpServletRequest.getHeader("Authorization");
                String base64Credentials = authorization.substring("Basic".length()).trim();
                byte[] credDecoded = Base64.getDecoder().decode(base64Credentials);
                String credentials = new String(credDecoded, StandardCharsets.UTF_8);
                final String username = credentials.split(":", 2)[0];
                final String password = credentials.split(":", 2)[1];
    
                //Check the username and password
                if (username.equals("admin") && password.equals("admin")) {
                    //continue
                    chain.doFilter(request, response);
                } else
                    throw new AuthenticationCredentialsNotFoundException("");
            } catch (Exception e) {
                throw new AuthenticationCredentialsNotFoundException("");
            }
    
        } else chain.doFilter(request, response);
    
      }
    
    }
    
  3. 仅为 JWT 编写主要安全配置并允许 /basic URL

    @Configuration
    @EnableWebSecurity
    public class JWTSecurityConfig extends WebSecurityConfigurerAdapter {
    
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/basic/**").permitAll().and()
                .csrf().disable()
                .antMatcher("/api/**")
                .addFilterAfter(new JWTAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic().disable();
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-28
    • 2020-02-29
    • 2020-04-19
    • 1970-01-01
    • 2018-10-22
    • 2017-01-12
    • 1970-01-01
    • 2016-05-09
    相关资源
    最近更新 更多