我在Web应用程序中使用spring security。
@Configuration
@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier(value = "loginServiceImpl")
private UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login**", "/resources/**", "/js/**", "/css/**")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and().exceptionHandling().accessDeniedPage("/403");
}
@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
}
和
@Service
public class LoginServiceImpl implements UserDetailsService {
@Autowired
private UserDao loginDao;
@Autowired
private HttpServletRequest request;
@Override
public UserDetails loadUserByUsername(String username) {
try {
final String ip = getClientIp(request);
net.liyan.psc.main.entity.main.User user = loginDao.findByUserNameForLogin(username);
if (user == null) throw new UsernameNotFoundException("User not found.");
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
if (isLocalZone(ip)) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE"));
} else {
// invalid IP
throw new Exception("Invalid IP.");
}
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
true,
true,
true,
true,
grantedAuthorities);
} catch (Exception ex) {
throw new UsernameNotFoundException("User not found.");
}
}
private static String getClientIp(HttpServletRequest request) {
// ...
}
boolean isLocalZone(String ip) {
//...
}
}
和loginController
@RequestMapping("/login")
public String loginForm(@ModelAttribute User users, ModelMap model,
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
String message = "";
if (error != null) {
message = URLDecoder.decode(Constant.LoginErrorMessage, "UTF-8");
} else if (logout != null) {
//message = "Logout successful !";
message = "";
}
model.addAttribute("message", message);
return "login";
}
如果我尝试使用无效的用户名和密码登录,则转到带有错误=“”的loginForm(),如果再次尝试使用无效的IP登录,则转到带有错误=“”的loginForm(),我该如何做两个州之间有什么不同? 如果IP无效,是否可以设置错误值或添加新参数?