首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java配置不起作用的Spring Boot自定义身份验证提供程序

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

Stack Overflow用户
提问于 2016-04-19 22:22:26
回答 3查看 38.9K关注 0票数 12

我正在尝试设置一个基于REST的web应用程序,其中前端使用Reactjs,后端使用Spring Boot。我还在尝试设置一个自定义身份验证提供程序,这就是我的问题所在。当尝试测试login API调用时,从不调用CustomAuthenticationProvider,而是使用默认的DaoAuthenticationProvider。这会导致登录报告"Bad credentials“。

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

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

代码语言:javascript
复制
curl -H "Content-Type: application/json" -X POST -d '{"username":"admin","password":"admin"}' http://localhost:8080/api/users/login

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

代码语言:javascript
复制
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);
}

}

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

代码语言:javascript
复制
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();
    }
}

为什么这不起作用?

EN

回答 3

Stack Overflow用户

发布于 2018-09-20 01:29:47

尝试在标题http上添加this thinks:

示例:

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2017-01-08 00:32:48

看看AuthenticationProvider类(分别是java文档)

方法authenticate期望:

代码语言:javascript
复制
 * Performs authentication with the same contract as
 * {@link org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}
 * @return a fully authenticated object including credentials. May return
 * <code>null</code> if the <code>AuthenticationProvider</code> is unable to support
 * authentication of the passed <code>Authentication</code> object. In such a case,
 * the next <code>AuthenticationProvider</code> that supports the presented
 * <code>Authentication</code> class will be tried.

如果您返回null,那么将调用下一个AuthenticationProvider,这是默认的。

我不确定这就是问题所在,但这可能是问题所在。尝试按照AuthenticationManager类告诉您的那样抛出BadCredentialsException:

代码语言:javascript
复制
 * <li>A {@link BadCredentialsException} must be thrown if incorrect credentials are
 * presented. Whilst the above exceptions are optional, an
 * <code>AuthenticationManager</code> must <B>always</B> test credentials.</li>
票数 -2
EN

Stack Overflow用户

发布于 2017-05-18 05:08:21

您必须以其他方式设置凭据。尝试查看用户名密码令牌的工作示例。但是您的"authenticate“函数需要设置凭据。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36721212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档