前后端不分离
@Service
public class UserServicesImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(User::getUsername,username);
User user = userMapper.selectOne(queryWrapper);
if(user == null){
throw new UsernameNotFoundException("用户不存在");
}
List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin_user");
return new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getPassword(),grantedAuthorities);
}
}
@EnableWebSecurity
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userServicesImpl")
private UserDetailsService detailsService;
@Autowired
private UserMapper userMapper;
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(CommonConstants.IGNORED_STATIC_RESOURCES.split(","));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.formLogin()
.loginPage("/toLogin")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/loginMethod")
.successHandler((request,response,authentication)->{
log.info(" authentication.getName():{}", authentication.getName());
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(User::getUsername,authentication.getName());
User user = userMapper.selectOne(queryWrapper);
log.info("Session中的用户: {}",user);
request.getSession().setAttribute("user",user);
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(new ObjectMapper().writeValueAsString(ResultVO.ok()));
out.flush();
out.close();
})
.failureHandler((request,response,authentication)->{
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(new ObjectMapper().writeValueAsString(ResultVO.fail()));
out.flush();
out.close();
})
.and().rememberMe().rememberMeParameter("remember");
http.authorizeRequests()
.antMatchers(CommonConstants.REQUEST_RESOURCES_PERMIT_ALL.split(","))
.permitAll()
.anyRequest().authenticated();
http.headers().frameOptions().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(detailsService).passwordEncoder(bCryptPasswordEncoder());
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}