首页 > 解决方案 > Spring Boot Spring 安全选项调用 403

问题描述

我正在使用 Spring Boot 2.x + Spring Security + JWT 为我的 Angular 5 应用程序创建 REST API。

我可以使用 POSTMAN 登录,但从 Angular 应用程序中,我的 OPTIONS 调用失败:

Request URL: http://localhost:8080/api/v1/login
Request Method: OPTIONS
Status Code: 403 
Remote Address: [::1]:8080

安全配置.java

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery).dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable().csrf().disable().authorizeRequests().antMatchers("/").permitAll().antMatchers("/").permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
    }
}

应用程序属性

# ===============================
# = DATA SOURCE
# ===============================
spring.datasource.url=jdbc:mysql://localhost:3306/some_db

spring.datasource.username=some_user
spring.datasource.password=some_password
spring.datasource.driverClassName=com.mysql.jdbc.Driver

# ===============================
# = JPA / HIBERNATE SETTINGS
# ===============================

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto = validate

# =============================================================
# = Spring Security / Queries for AuthenticationManagerBuilder  
# =============================================================

spring.queries.users-query=select email, password from users where email=?
spring.queries.roles-query=select u.email, r.role from users u inner join user_role ur on(u.user_id=ur.user_id) inner join role r on(ur.role_id=r.role_id) where u.email=? 

# ===========================
# = JSON WEB TOKEN SETTINGS  
# ===========================

jwt.secret= JWTSuperSecretKey
jwt.expiration = 604800000

邮差:

发布:http://localhost:8080/api/v1/login

内容类型:application/x-www-form-urlencoded

这是角度方面的标题问题吗?

标签: spring-bootspring-securityangular5

解决方案


您禁用 CORS,这意味着您的服务器不会告诉前端允许对任何来源的请求,但它自己。通过告诉服务器接受来自另一个来源的请求,例如localhost:4200GET、PUT、POST、DELETEOPTIONS 方法,您的应用程序应该可以工作。

下面的设置比它需要的要复杂一些,但它可以让事情保持整洁。

允许的来源的定义应该放在 application.yml 例如

cors:
  allowed-origins:
    - https://localhost:4200
    - http://localhost:4200
    - http://127.0.0.1:4200
    - https://127.0.0.1:4200

然后添加两个文件,一个用于加载配置...

@Configuration
@ConfigurationProperties("cors")
public class CorsConfig {
    private List<String> allowedOrigins = new ArrayList<>();
    private String[] allowedMethods = {
        HttpMethod.GET.name(),
        HttpMethod.HEAD.name(),
        HttpMethod.POST.name(),
        HttpMethod.PUT.name(),
        HttpMethod.DELETE.name()
    };

    public List<String> getAllowedOrigins() {
        return allowedOrigins;
    }

    public String[] getAllowedOriginsArray() {
        return getAllowedOrigins().toArray(new String[0]);
    }

    public String[] getAllowedMethods() {
        return allowedMethods;
    }
}

......还有一个让它发挥作用。

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    private final CorsConfig corsConfig;

    public WebMvcConfig(CorsConfig corsConfig) {
    this.corsConfig = corsConfig;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins(corsConfig.getAllowedOriginsArray())
            .allowedMethods(corsConfig.getAllowedMethods());
    }
}

推荐阅读