Spring Security无法使用自定义内容类型

时间:2018-11-22 06:07:27

标签: java spring spring-boot spring-security

我在Spring Boot Rest API应用程序中具有基本的Spring Security。我有一个自定义内容类型作为标头的一部分。如果内容类型为application/json,则可以正常工作。但是使用自定义标头,即使凭据不匹配,它也只会传递所有请求。

@Component
public class MyAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    /** {@inheritDoc} */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        final PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 - " + authException.getMessage());
    }

    /** {@inheritDoc} */
    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("modelsDb");
        super.afterPropertiesSet();
    }
}

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * authEntryPoint : is authentication entrypoint of this application.
     */
    @Autowired
    private MyAuthenticationEntryPoint authEntryPoint;

    /**
     * env : provides the environment of the application.
     */
    @Autowired
    private Environment env;

    /** {@inheritDoc} */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic().authenticationEntryPoint(authEntryPoint).and().sessionManagement().disable();
    }

    /**
     * Configures the rules for authentication for this application.
     * 
     * @param auth : authentication builder object.
     * @throws Exception : throws exception in case of any issues with authentication.
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()).withUser(env.getProperty("spring.security.user.name")).password(env.getProperty("spring.security.user.password")).roles("USER");
    }

    /**
     * Configure the Password encoder.
     * 
     * @return BCryptPasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

我在* .properties中拥有我的用户凭据

spring.security.user.name=sam
spring.security.user.password=$2a$10$nwKvBSi2QfhfghfhFIOYmRrtyertyrtyrthdKV3vvaH8JnkhOS  #Bcrypt password welcome

我正在使用邮递员在我拥有的“授权”标签中进行测试

type: Basic Auth
username :sam
password : welcome

“标题”标签中的内容类型:

application/vnd.com.sample.v1+json

因此,如何使安全性适用于自定义内容类型。我应该明确设置内容类型吗?请帮忙!

0 个答案:

没有答案