java - 具有 Java 配置的 Spring Boot 自定义身份验证提供程序不起作用

标签 java spring rest authentication spring-security

我正在尝试设置一个基于 REST 的 Web 应用程序,其中前端使用 Reactjs,后端使用 Spring Boot。我也在尝试设置自定义身份验证提供程序,这就是我的问题开始的地方。尝试测试登录 API 调用时,从未调用 CustomAuthenticationProvider,而是使用默认的 DaoAuthenticationProvider。这会导致登录报告“凭据错误”。

我已将一个小示例应用程序上传到 github:spring-boot-auth-demo

为了测试登录 API,我使用以下 curl:

curl -H "Content-Type: application/json" -X POST -d '{"username":"admin","password":"admin"}' http://localhost:8080/api/users/login

CustomAuthenticationProvider 执行简单的用户名/密码检查并返回一个 UsernamePasswordAuthenicationToken 对象。

package no.bluebit.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

private static final Logger logger =     LoggerFactory.getLogger(CustomAuthenticationProvider.class);

public CustomAuthenticationProvider() {
    logger.info("*** CustomAuthenticationProvider created");
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if(authentication.getName().equals("admin")  && authentication.getCredentials().equals("admin")) {
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), grantedAuths);
    } else {
        return null;
    }

}

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

}

CustomAuthenticationProvider 使用 SecurityConfiguration 类连接。单步执行代码时,我可以看到 CustomAuthenicationProvider 不在用于对传入请求进行身份验证的提供程序列表中。

package no.bluebit.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/users/login").permitAll()    // Permit access for all to login REST service
                .antMatchers("/").permitAll()                   // Neccessary to permit access to default document
            .anyRequest().authenticated().and()                 // All other requests require authentication
            .httpBasic().and()
            .logout().and()
            .csrf().disable();
    }
}

为什么这不起作用?

最佳答案

尝试在 header http 上添加这认为:

例子:

const headers = new HttpHeaders();
headers.set('Access-Control-Allow-Origin', '*');
headers.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
headers.set('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept, x- 
requested-with, Cache-Control');
headers.set('Content-Type', 'application/json');


this.http.post('http://localhost:8081/loginAngular',
   JSON.stringify({user: 'sdasd', password: 'dasdasd', estado: 'dasdasd', idUsuario: 1, resultado: 'asdasd'}) ,
  {headers: new HttpHeaders().set('Content-Type', 'application/json')}).subscribe(data => {
  console.log(' Data: ' + data);

});

我用 spring security 和 angular 制作了这个应用程序! 正面:https://github.com/nicobassart/angularforHidra 返回:https://github.com/nicobassart/hidra_server

关于java - 具有 Java 配置的 Spring Boot 自定义身份验证提供程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36721212/

相关文章:

用于无状态计算的 REST 服务

java - Spring Boot 2.7 EOL 后的缓解措施

java - Coldfusion 和 Java 如何验证 punycode IDN

Java循环星型模式-算法优化

java - Hive jdbc.query(sql, rowmapper) 抛出 UnCatogarized 异常

spring - 如何访问 Spring MVC REST Controller 中的 HTTP header 信息?

java - 为什么 hibernate 不删除行?

spring - 如何保证Spring @Autowired注入(inject)在构造函数中可以访问

java - 如何在不同的类中使用 Spring Bean

java - Swagger 配置 - 访问 swagger.json 时出现 404