配置依赖
大致所需依赖如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yunhe</groupId>
<artifactId>SpringBootDemo3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootDemo3</name>
<description>SpringBootDemo3</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 该依赖无法直接生成,需手动添加,不然获取不到权限 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>2.2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置application配置文件
server.port=8080
#配置数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123
#thymeleaf 缓存关闭
spring.thymeleaf.cache=false
#mybatis驼峰
mybatis.configuration.map-underscore-to-camel-case=true
#设置静态资源位置
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/
编写Security配置文件
package com.yunhe.config;
import com.yunhe.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* spring security配置文件
*/
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccountService accountService;
/**
* 认证数据管理,连接service
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(accountService);
}
/**
* 设置认证的访问配置
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
//放行资源
http.authorizeRequests().antMatchers("/login.html","/error.html","/register.html").permitAll();
//角色名不加 ROLE_ ,系统自动添加
http.authorizeRequests().antMatchers("/**").hasAnyRole("USER","ADMIN");
//设置资源必须登录成功后进行访问
http.authorizeRequests().antMatchers("/**").authenticated();
//设置登录页面
http.formLogin().defaultSuccessUrl("/index").loginPage("/login.html").loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
.failureUrl("/error.html");
//设置退出登录
http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html");
//关闭跨域
http.csrf().disable();
//配置403异常处理
http.exceptionHandling().accessDeniedPage("/authizeError.html");
}
//定义加密器
@Bean
public PasswordEncoder createPasswordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
}
编写业务层方法
业务层接口要继承UserDetailsService方法
package com.yunhe.service.impl;
import com.yunhe.service.AccountService;
import com.yunhe.dao.AccountDao;
import com.yunhe.entity.Account;
import com.yunhe.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
/**
* 登录认证
* @param username
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//调用持久层获取用户信息
Account account = accountDao.findAccountByUsername(username);
//创建一个认证对象
User user = new User(account.getUsername(),account.getPassword(),true,true,true,true,getRoles(account.getRoles()));
return user;
}
//获取用户的授权角色
private Collection<? extends GrantedAuthority> getRoles(List<Role> roles) {
ArrayList<SimpleGrantedAuthority> sgas = new ArrayList<>();
//遍历查询到的角色集合
for (Role role : roles) {
SimpleGrantedAuthority sa = new SimpleGrantedAuthority("ROLE_" + role.getRolename());
sgas.add(sa);
}
return sgas;
}
}
编写持久层方法
持久层要查询用户信息以及权限信息,要查询两个表+中间表
import com.yunhe.entity.Account;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface AccountDao {
@Select("select id,username,password from account where username=#{username}")
@Results({
@Result(property = "roles",javaType = List.class,column ="id",many = @Many(select = "com.yunhe.dao.RoleDao.findRolesByAid"))
})
Account findAccountByUsername(String username);
}
import com.yunhe.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface RoleDao {
@Select("select r.* from role_account ra,role r where ra.rid = r.id and ra.aid=#{id}")
List<Role> findRolesByAid(int id);
}
登录准备
先来一个登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="http://localhost:8080/"/>
<title>登录</title>
</head>
<body>
<form action="login" method="post">
账号:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<button type="submit">登录</button>
<button><a href="register.html">注册</a></button>
</form>
</body>
</html>
由于在Security配置文件中配置了登录成功跳转页面、登录页面、登录方法,而在项目中使用了thymeleaf模板引擎,所以需要进行控制层跳转。
控制层跳转主页面:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("index")
public String index(){
return "index";
}
}
配置文件中的其他页面如error页面、403页面自行设置即可。