目录
一.创建项目骨架
连接数据库 创建启动类
spring.profiles.active=pro
server.port=8082
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/users_a?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
mybatis-plus.mapper-locations=classpath:mapper/*Dao.xml
logging.level.root=info
logging.level.cn.woniu.springbootdays1.dao=debug
@MapperScan("com.security02.dao")
@SpringBootApplication
public class Security02Application {
public static void main(String[] args) {
SpringApplication.run(Security02Application.class, args);
}
}
1.1导入依赖
<!--springboot整合security坐标-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <optional>true</optional>
</dependency>
<!-- mysql-connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1.2 创建domain包
@Data
public class Users {
private Integer id;
private String username;
private String password;
private String account;
}
1.3 创建dao包
public interface UserDao {
/**
* 根据账号查询用户信息:注意账号在表中是唯一的存在
* @param account
* @return
*/
Users queryUserAccount(String account);
}
1.3 创建service包
@Service
public class SecurityService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired(required = false)
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Users users = userDao.queryUserAccount(username);
//根据username.去数据库查该用户的信息
try {
return new User(users.getAccount(),passwordEncoder.encode(users.getPassword()),
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin,ROLE_insert2,ROLE_insert3,select"));
} catch (Exception e) {
throw new UsernameNotFoundException("用户名或密码输入错误");
}
//根据用户查出来的用户信息和页面的传过来的username与password做对比
}
}
1.4创建controllerbao
@RestController
public class LoginController {
@RequestMapping("hello")
public String Login(){
return "hello";
}
@RequestMapping("insert")
public String addUserInfo(){
return "insert";
}
@RequestMapping("update")
public String update(){
return "update";
}
@RequestMapping("delete")
public String delete(){
return "delete";
}
@RequestMapping("select")
//@PreAuthorize("hasAuthority('select')")
@PreAuthorize("hasAnyAuthority('select1','select2')")
public String select(){
return "select";
}
}
1.5创建config配置包
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)//启用注解判断用户权限
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityService securityService;
/**
* 密码加密
* @return
*/
@Bean//通过Bean将PasswordEncoder传入到方法里面
public PasswordEncoder getPassword(){
return new BCryptPasswordEncoder();
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(securityService).passwordEncoder(getPassword());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //告诉security使用自定义的登录页面了
.loginPage("/login.html") //告诉secrity页面在哪
.loginProcessingUrl("/dologin") //告诉表单提交的地址
// .defaultSuccessUrl("/index.html")
.successHandler(new LoginSuccessHandler())//注册登录成功后的处理类
.permitAll();
// http.authorizeRequests() //配置请求权限
// //hasAuthority("insert") 只有insert校色才能访问insert方法
// // .antMatchers("/insert").hasAuthority("insert")//设置权限 配置insert路径只能是拥有insert角色才能欧进行访问
// //
// .antMatchers("/insert").
// hasAnyAuthority("insert1","insert2")
// .antMatchers("/update").hasAnyRole("insert2,insert3")
// .anyRequest().authenticated(); //所有请求都兰街
//我像给insert方法拥有insert1 或者insert2...多种访问
http.csrf().disable();
}
1.6创建返回类
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//设置字符集
httpServletResponse.setContentType("application/json;charset=UTF-8");
PrintWriter pw=httpServletResponse.getWriter();
pw.println("dl");
pw.flush();
pw.close();
}
}
1.7创建mapper包
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.security02.dao.UserDao">
<select id="queryUserAccount" resultType="com.security02.damamin.Users">
SELECT id,username,account,password FROM users where account = #{account}
</select>
</mapper>