我知道如果将它作为方法参数包含在内,Spring会将主体传递给控制器的方法。Spring Security - 实现UserDetailsService
我试图通过实施UserDetailsService
扩展这个功能:
我创建了一个名为CustomUserDetails
类,它扩展org.springframework.security.core.userdetails.User
我创建了一个名为CustomUserDetailsService
服务实现UserDetailsService
异常
HTTP状态500 - 请求处理失败;嵌套的异常是 java.lang.ClassCastException: org.springframework.security.authentication.UsernamePasswordAuthenticationToken 不能转换到com.demo.model.CustomUserDetails
在我的控制器方法下面的行抛出异常:
CustomUserDetails userDetails = (CustomUserDetails) principal;
Controller.java
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal, HttpServletRequest request) {
// Throws exception here
CustomUserDetails userDetails = (CustomUserDetails) principal;
System.out.println(userDetails.getFirstName());
// Tried this and it also throws exception
// User cannot be cast to CustomUserDetails
//Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//CustomUserDetails userDetails = (CustomUserDetails)auth.getPrincipal();
// Render template located at
// src/main/resources/templates/dashboard.html
modelAndView.setViewName("dashboard");
return modelAndView;
}
SecurityConfiguration.java
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private DataSource dataSource;
@Value("${spring.queries.users-query}")
private String usersQuery;
@Value("${spring.queries.roles-query}")
private String rolesQuery;
@Autowired
SecurityHandler successHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/register*").permitAll()
.antMatchers("/reset").permitAll().antMatchers("/forgot").permitAll().antMatchers("/grid").permitAll()
.antMatchers("/login").permitAll().antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
.authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error")
.defaultSuccessUrl("/dashboard").successHandler(successHandler).usernameParameter("email")
.passwordParameter("password").and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout").and().exceptionHandling().accessDeniedPage("/access-denied");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/error**", "/resources/**", "/static/**", "/css/**", "/js/**", "/img/**");
}
}
CustomUserDetails.java
public class CustomUserDetails extends org.springframework.security.core.userdetails.User {
public CustomUserDetails(String username, String password,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
CustomUserDetailsService.java
@Service
public class CustomUserDetailsService implements UserDetailsService{
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException{
if(StringUtils.isEmpty(userName))
throw new UsernameNotFoundException("User name is empty");
//if you don't use authority based security, just add empty set
Set<GrantedAuthority> authorities = new HashSet<>();
CustomUserDetails userDetails = new CustomUserDetails(userName, "", authorities);
userDetails.setFirstName("Testing: " + new Date());
return userDetails;
}
}
的'Principal'你得到的是'Authentication'对象,而不是你的用户。在那你可以调用'getPrincipal'来获得实际的用户。 (这也是类抛出异常告诉你的)。 –
你可以发布实际抛出异常的代码吗? – rptmat57
@ rptmat57当然我添加了控制器方法代码 –