java - CORS Spring Security Oauth2

标签 java spring spring-boot spring-security oauth-2.0

我对 CORS Spring Security Oauth2 有疑问。

这是我的类 CustomAuthenProvider.java

@Component
public class CustomAuthenProvider implements AuthenticationProvider {

  private static final Logger logger = LogManager.getLogger(CustomAuthenProvider.class);

  @Autowired(required = false)
  private HttpServletRequest request;

  @Autowired
  private LdapService ldapService;

  @Value("${key.twofactor}")
  private String key;

  @Override
  public Authentication authenticate(Authentication authentication) {

    boolean authorizeLdap = ldapService.authorizeLDAP(authentication.getName(),
        authentication.getCredentials().toString());
    Totp totp = new Totp(key);

    if (!authorizeLdap || !totp.verify(request.getParameter(Constant.OTP))) {
      logger.info("Login Fail");
      return null;
    }
    Authentication auth = new UsernamePasswordAuthenticationToken(authentication.getName(),
        authentication.getCredentials().toString(), getAuthorityAdmin());
    return auth;

  }

  private List<SimpleGrantedAuthority> getAuthorityAdmin() {
    return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
  }
}

这是我的 SecurityConfig.java 类

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private CustomAuthenProvider customAuthenProvider;

  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(customAuthenProvider);
  }

  @SuppressWarnings("deprecation") // For NoOpPasswordEncoder
  // Using NoOpPasswordEncoder for simplicity's sake
  @Bean
  public PasswordEncoder passwordEncoder() {
    return NoOpPasswordEncoder.getInstance();
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().anonymous().disable().authorizeRequests()
        .antMatchers("/api-docs/**").permitAll();
  }

  @Bean
  public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration
        .setAllowedMethods(Arrays.asList("GET", "POST", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
    configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
  }

}

我使用 Angular 7 作为前端。

调用 API 192.168.0.109:8182/oauth/token 时显示错误:

2zone-evergreen.js:2952 OPTIONS http://192.168.0.109:8182/oauth/token 401
 Access to XMLHttpRequest at 'http://192.168.0.109:8182/oauth/token' from origin 'http://192.168.0.113:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我不知道为什么会出现消息“未经授权”。

有人可以帮我吗?

提前致谢。 :)

最佳答案

modify as below and try 

    @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().anonymous().disable().authorizeRequests()
                     .antMatchers("/api/auth/**")
                        .permitAll()
                    .antMatchers(HttpMethod.GET, "/api/**", "/api/**")
                        .permitAll();

}

关于java - CORS Spring Security Oauth2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58338306/

相关文章:

java - 如何将java数据库服务器嵌入到分布式jar中?

java - Python或Java模块在服务器端渲染HTML页面并获取DOM对象

java - 第二次调用 HttpServletResponse

java - Spring Security 登录总是登陆一个没有消息的错误页面

spring - java 9模块从A和B读取包X

java - Spring Boot 中的 ManyToMany 映射问题

spring - 获取请求 header 名称和值

json - Spring Data Rest 不明确关联异常

java - Java Spring 应用程序的巴西时区

java - 在 Spring Boot 中读取 MacOs 环境变量