【发布时间】:2015-06-02 20:13:29
【问题描述】:
我在使用 Spring 安全认证时遇到了一些问题。 在我的应用程序中,一切都运行良好(CRUD 操作运行良好),但登录尝试失败。
这是我的代码(我在下面用 cmets 标记,其中 userDAO 为 null,这是身份验证失败的原因):
@Service
public class UserServiceImpl implements UserService, UserDetailsService {
@Autowired
UserDAO userDAO;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDAO.getUserByUsername(username); //userDAO == null Causing NPE
if (user == null)
throw new UsernameNotFoundException("Oops!");
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority(user.getRole()));
return new org.springframework.security.core.userdetails
.User(user.getLogin(), user.getPassword(), authorities);
}
@Override
public List<User> getUsers() {
return userDAO.getUsers();//userDAO !=null
}
//rest of code skipped
我的 SecurityConfig 看起来像这样
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
UserServiceImpl userService = new UserServiceImpl();
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
//rest of code skipped
我标记了我在哪里获得 NPE,但我不知道如何解决这个问题。整个配置是基于 Java 的,您可以在这里查看更多详细信息 HERE
编辑:getUsers() 在控制器中以这种方式调用:
@Controller
public class LoginController {
@Autowired
UserService userService;
@RequestMapping(value = "/dashboard")
public ModelAndView userDashboard(){
ModelAndView modelAndView = new ModelAndView("Dashboard");
List<User> userList = userService.getUsers();
modelAndView.addObject("users", userList);
return modelAndView;
}
并且在这种情况下(调用 userService.getUsers() 时)userDAO 不为空
尝试像 Bohuslav Burghardt 建议的那样修复它,我得到了
method userDetailsService in class org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder cannot be applied to given types;
required: T
found: com.gi.service.UserService
reason: inferred type does not conform to upper bound(s)
inferred: com.gi.service.UserService
upper bound(s): org.springframework.security.core.userdetails.UserDetailsService
排队 auth.userDetailsService(userService);
【问题讨论】:
标签: java spring spring-security