0

我正在使用Spring-Boot、Spring Security基本身份验证。我将通过 RESTful API 调用从我用 AngularJS 编写的客户端应用程序发送登录 URL。

一切都按预期工作。数据库中的所有用户在SecurityConfiguration.java中配置如下。

@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {

    List<User> users = userService.getUsers();
    for (User user : users) {
        auth.inMemoryAuthentication().withUser(user.getUserName()).password(user.getPassword())
                .roles(user.getRole().getName());
    }
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable().authorizeRequests().antMatchers("/server/rest/secure/**")
    .hasRole("ADMIN").and()
            .httpBasic().realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint());
}

@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() {
    return new CustomBasicAuthenticationEntryPoint();
}

CustomBasicAuthenticationEntryPoint.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

@Override
public void commence(final HttpServletRequest request, 
        final HttpServletResponse response, 
        final AuthenticationException authException) throws IOException, ServletException {

    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");

    PrintWriter writer = response.getWriter();
    writer.println("HTTP Status 401 : " + authException.getMessage());
    response.setHeader("WWW-Authenticate", "FormBased");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

@Override
public void afterPropertiesSet() throws Exception {
    setRealmName("MY_TEST_REALM");
    super.afterPropertiesSet();
}
}

因此,如果我注册了一个新用户,该用户将插入数据库但未在上述实现中添加。所以认证失败。

每当我注册新用户时,如何刷新上述实现

4

1 回答 1

2

使用 db 进行身份验证时,您应该执行以下操作:

@Service("userDetailsService")
@Transactional
public class MUserDetailService implements UserDetailsService {

    @Autowired
    AppUserDao appUserDao;

    @Override
    public UserDetails loadUserByUsername(final String appUserName) throws UsernameNotFoundException {

        AppUser appUser = appUserDao.findByName(appUserName);
        if (appUser == null) throw new UsernameNotFoundException(appUserName);
        else{
            return new User(appUser.getUsername(),appUser.getPassword(),appUser.getActive(),true,true,true,getGrantedAuthorities(appUser));
        }
    }

    private List<GrantedAuthority> getGrantedAuthorities(AppUser appUser){
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        for (Authority authority : appUser.getAuthorities()){
            authorities.add(new SimpleGrantedAuthority(authority.getAuthorityName()));
        }
        return authorities;
    }
}

然后定义 SecurityConfiguration 如下:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}
于 2017-09-08T19:33:18.757 回答