创建项目
选择引入springSecurity web mybatis 和mysql连接。
用mybatis逆向工程构建mapper和实体类
配置项目
boot启动类处加上@mapperScan扫描mapper所在的包
@SpringBootApplication
@MapperScan(basePackages = "com.maaoooo.vhr_serve.mapper")
public class VhrServeApplication {
public static void main(String[] args) {
SpringApplication.run(VhrServeApplication.class, args);
}
}
数据库配置,使用druid
spring.datasource.url=jdbc:mysql://localhost:3306/vhr?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
配置springsecurity
在用户实体类上实现UserDetails,重写方法
@Override
public boolean isAccountNonExpired() { //是否没有过期
return true;
}
@Override
public boolean isAccountNonLocked() {//是否没有锁定
return true;
}
@Override
public boolean isCredentialsNonExpired() {//密码是否没有过期
return true;
}
@Override
public boolean isEnabled() {//是否有效 注意要删除原本的enable的get方法
return enabled;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {//配置角色
return null;
}
service实现UserDetailsService
角色先不配
/**
* @author lzr
* @date 2020 09 13 19:20
* @description
*/
public class HrService implements UserDetailsService {
@Autowired
private HrMapper hrMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Hr hr = hrMapper.selectByPassword(username);
if(hr==null){
throw new UsernameNotFoundException("用户名不存在");
}
return hr;
}
}
完善mapper和mapper.xml的方法和查询语句
配置SecurityConfig
前后端分离,登陆成功不做页面跳转,只返回json告知前端。
package com.maaoooo.vhr_serve.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.maaoooo.vhr_serve.model.Hr;
import com.maaoooo.vhr_serve.model.RespBean;
import com.maaoooo.vhr_serve.service.HrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
/**
* @author lzr
* @date 2020 09 13 19:46
* @description
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private HrService hrService;
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(hrService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/doLogin")
.loginPage("/login")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter writer = resp.getWriter();
Hr hr = (Hr) authentication.getPrincipal();
hr.setPassword(null);
String s = new ObjectMapper().writeValueAsString(hr);
RespBean.ok("登陆成功!", hr);
writer.write(s);
writer.flush();
writer.close();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter writer = resp.getWriter();
RespBean respBean = RespBean.error("登陆失败!");
if (e instanceof LockedException) {
respBean.setMsg("账户被锁定,请联系管理员!");
} else if (e instanceof CredentialsExpiredException) {
respBean.setMsg("密码过期");
} else if (e instanceof AccountExpiredException) {
respBean.setMsg("账户过期");
} else if (e instanceof DisabledException) {
respBean.setMsg("账户被禁用");
} else if (e instanceof BadCredentialsException) {
respBean.setMsg("用户名或密码错误");
}
String s = new ObjectMapper().writeValueAsString(respBean);
writer.write(s);
writer.flush();
writer.close();
}
})
.permitAll()
.and()
.logout().logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
RespBean respBean = RespBean.ok("已注销");
String s = new ObjectMapper().writeValueAsString(respBean);
PrintWriter writer = resp.getWriter();
writer.write(s);
writer.flush();
writer.close();
}
})
.permitAll()
.and()
.csrf().disable();
}
}