Spring编程REST认证服务

时间:2014-03-16 13:37:47

标签: spring spring-security http-basic-authentication

我正在使用Spring 3开发API。我希望所有用户在执行请求时都登录,因此我尝试实现Basic HTTP Auth。我不想使用XML(大部分文档都使用XML)。

服务器当前对每个请求回复401,我的网络浏览器不会要求我进行身份验证。我哪里错了?

我搜索了很多网站,这是我到目前为止所得到的:

申请类:

@Configuration
@EnableJpaRepositories
@EnableAutoConfiguration
@ComponentScan
public class Application
{
@Bean
    public BasicAuthenticationFilter basicAuthenticationFilter(BasicAuthenticationEntryPoint basicAuthenticationEntryPoint,
                                                                AuthenticationManager authenticationManager)
    {
        BasicAuthenticationFilter basicAuthenticationFilter = new BasicAuthenticationFilter(authenticationManager, basicAuthenticationEntryPoint);
        return basicAuthenticationFilter;
    }

    @Bean
    public UserDetailsService userDetailsService()
    {
        return new PersonService();
    }

    @Bean
    public AuthenticationManager authenticationManager()
    {
        return new AuthenticationManagerImpl();
    }

    @Bean
    public AuthenticationProvider authenticationProvider()
    {
        return new CustomAuthenticationProvider();
    }

    @Bean
    public BasicAuthenticationEntryPoint basicAuthenticationEntryPoint()
    {
        BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
        basicAuthenticationEntryPoint.setRealmName("Doccto");
        return basicAuthenticationEntryPoint;
    }
}

我的自定义AuthenticationManager

@Component
public class AuthenticationManagerImpl implements AuthenticationManager
{
    @Autowired
    protected AuthenticationProvider authenticationProvider;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
        return this.authenticationProvider.authenticate(authentication);
    }
}

PersonService.class:

@Service
public class PersonService implements UserDetailsService
{
    @Autowired
    protected PersonRepository personRepository;

    @Override
    public Person loadUserByUsername(String s) throws UsernameNotFoundException
    {
        return this.personRepository.getUserByEmail(s);
    }
}

CustomAuthenticationProvider

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider
{
    @Autowired
    protected PersonService personService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        Person person = this.personService.loadUserByUsername(username);

        if (person == null)
            {
                throw new BadCredentialsException("Username not found.");
            }

        if (!password.equals(person.getPassword()))
            {
                throw new BadCredentialsException("Wrong password.");
            }

        Collection<? extends GrantedAuthority> authorities = person.getAuthorities();

        return new UsernamePasswordAuthenticationToken(username, password, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass)
    {
        return true;
    }
}

SecurityConfig.class

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
            .authorizeRequests()
            .antMatchers("/api/**").hasRole("USER")
            .anyRequest().authenticated();
    }

我认为就是这样。

1 个答案:

答案 0 :(得分:1)

我终于找到了解决方案。 我必须将所有代码片段绑定在SecurityConfig中,如

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Autowired
    protected BasicAuthenticationFilter filter;
    @Autowired
    protected AuthenticationProvider    authenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
            .addFilter(filter)
            .authenticationProvider(authenticationProvider)
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/api/**").hasRole("USER")
            .anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
    }
}