关于Spring Security如何工作原理在这里就不介绍了。因为我也不懂
@Override
public UserDetails loadUserByUsername(String mobile) throws UsernameNotFoundException {
String[] str = mobile.split(BusinessConstant.Constants.KEY_SPLIT_SYMBOL_2);
if(null == str) {
throw new LoginAccessException("请输入用户名");
} else if(1 == str.length) {
throw new LoginAccessException("请输入用户名不存在");
} else if(str.length > 2) {
throw new LoginAccessException("输入用户名不合法,请不要输入非法字符");
}
UserInfo record = userInfoMapper.findBymobile(str[0], str[1]);
if (record == null) {
throw new LoginAccessException("该用户不存在");
} else if(record.getStatus() != 1) {
throw new LoginAccessException("该用户已被禁用, 请联系管理员");
// throw new UsernameNotFoundException("该用户已不是正常状态, 请联系管理员");
}
List<GrantedAuthority> authorities=new ArrayList<>();
try {
//权限如果前缀是ROLE_,security就会认为这是个角色信息,而不是权限,例如ROLE_MENBER就是MENBER角色,CAN_SEND就是CAN_SEND权限
List<String> urlList = new ArrayList<String>();
//权限
// String perId = this.getPerByUid(record.getId());//根据用户获取权限列表字符串
// urlList.addAll(permissionService.getPermission(perId));
for(String url:urlList){
if(StringUtils.isNotBlank(url)){
authorities.add(new SimpleGrantedAuthority(url));
}
}
//客户权限
BaseVO basevo=new BaseVO();
if (!Tools.isContains(authorities, "ROLE_1")) {
basevo.setUid(record.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
return new UserSession(record.getAccount(),record.getPassword(),authorities,record);
}
上面代码中的LoginAccessException必须继承AccessDeniedException类,而我开始抛出的异常是UsernameNotFoundException("填写需要显示的文本")最后在authenticate()方法中验证
@Component
public class CustomAuthenticationProvider extends DaoAuthenticationProvider {
public CustomAuthenticationProvider(UserDetailsService userDetailsService,Md5PasswordEncoder passwordEncoder){
this.setUserDetailsService(userDetailsService);
this.setPasswordEncoder(passwordEncoder);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
CustomWebAuthenticationDetails details = (CustomWebAuthenticationDetails) authentication.getDetails();
if (details.getCaptcha().toLowerCase().equals(details.getSessionCaptcha().toLowerCase())) {
try {
return super.authenticate(authentication);
} catch (Exception e) {
String message = "账户或密码错误,请重试";
String errorMessage;
if(!StringUtils.isEmpty(errorMessage = e.getMessage()) && !"Bad credentials".equals(errorMessage)) {
message = errorMessage;
}
throw new BadCredentialsException(message);
}
} else {
throw new BadCredentialsException("验证码错误");
}
}
}
必须要定义自己的异常类,如何如何spring自带的Exception话,得到的异常文本无论你如何输入,如何写,如何传值得到只有一个相同的,如:UsernameNotFoundException是Bad credentials文本
当前这只是我的问题记录,可能不对,但只作为问题记录一下,防止后期再犯!