您好,登錄后才能下訂單哦!
1、學習這個用了4天終于弄出來
2、剛調試成功做個筆記
<?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 http://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.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.eSpringSecurity</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<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.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!--配置js.scc-->
<!-- https://mvnrepository.com/artifact/org.webjars/bootstrap -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.webjars.bower/jquery -->
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#熱部署文件,頁面不產生緩存,及時更新# 開發階段務必關閉緩存 (=false)
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#logging.level.com.dy.springboot.server.mapper=debug
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
server.port=8080
spring:
datasource:
username: root
# password: root
password: 123456
url: jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置監控統計攔截的filters,去掉后監控界面sql無法統計,'wall'用于防火墻
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
# 指定全局配置文件位置
config-location: classpath:generator/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mapping/*.xml
# schema:
# - classpath:department.sql
log4j.rootCategory=INFO, stdout , logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[SeleniumAutoConsole] %p [%t] %C.%M(%L) | %m%n
log4j.appender.logfile.encoding=UTF-8
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=logs/logs.log
#log4j.appender.logfile.DatePattern='.'yyyy-MM-dd'.log'
#log4j.appender.logfile.Append=true
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d-[SeleniumAutoFile] %p [%t] %C.%M(%L) - %m%n
package com.espringsecurity.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author liwen406
* @Title: DruidConfig
* @Description:
* @date 2018/12/21 / 22:43
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
/**
* 配置Druid的監控
* 1、配置一個管理后臺的Servlet
* @return
*/
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "123456");
////默認就是允許所有訪問
initParams.put("allow", "");
initParams.put("deny", "192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
/**2、配置一個web監控的filter*/
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
package com.espringsecurity.config;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import java.util.Properties;
/**
*配置文件
* @author liwen406
* @date 2019-04-20 12:14 2019-04-20 13:20
*/
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
/**
* 目的防止駝峰命名規則
* @return
*/
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
/**
* 分頁插件
* @return
*/
@Bean
public PageHelper pageHelper() {
// System.out.println("MyBatisConfiguration.pageHelper()");
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author liwen406
* @Title: MyPasswordEncoder
* @Description:
* @date 2019/5/4 / 18:20
*/
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
/**
* @author liwen406
* @Title: WebMvcConfig
* @Description:
* @date 2019/4/29 / 13:00
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
import com.espringsecurity.pojo.User;
import com.espringsecurity.service.PasswordEncoder;
import com.espringsecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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.web.util.matcher.AntPathRequestMatcher;
import javax.annotation.Resource;
/**
* @author liwen406
* @Title: WebSecurityConfig
* @Description:
* @date 2019/5/4 / 18:18
*/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private UserService<User> userService;
/**
* 認證請求規則
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
// 注銷賬號
http.logout().logoutSuccessUrl("/");
/****************** 默認的 ****************/
// 默認登錄表單
http.formLogin();
// 記住我
http.rememberMe();
/****************** 定制的 ****************/
// 定制頁面和參數,默認名稱:username,password
http.formLogin().loginPage("/login").usernameParameter("username").passwordParameter("passowrd");
// 定制記住我
http.rememberMe().rememberMeParameter("remember");
}
/**
* 授權
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(new PasswordEncoder());
}
}
package com.espringsecurity.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author liwen406
* @Title: PageController
* @Description:
* @date 2019/5/4 / 18:20
*/
@Controller
public class PageController {
@GetMapping({"/", "", "/index"})
public String index() {
return "index";
}
// 定制的登錄表單
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("level1")
@ResponseBody
public String level1() {
return "level1 擁有角色VIP1";
}
@GetMapping("level2")
@ResponseBody
public String level2() {
return "level2 擁有角色VIP2";
}
@GetMapping("level3")
@ResponseBody
public String level3() {
return "level3 擁有角色VIP3";
}
}
import com.espringsecurity.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
/**
* @author liwen406
* @Title: UserDao
* @Description:
* @date 2019/5/4 / 18:58
*/
@Mapper
public interface UserDao {
@Select("SELECT * from usersys WHERE username = #{userName}")
User findByUsername(String username);
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author liwen406
* @Title: User
* @Description:
* @date 2019/5/4 / 18:33
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String userName;
private String password;
private String roles;
}
import cn.hutool.core.util.StrUtil;
import com.espringsecurity.dao.UserDao;
import com.espringsecurity.pojo.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
/**
* @author liwen406
* @Title: UserService
* @Description:
* @date 2019/5/4 / 18:32
*/
@Log4j2
@Service
public class UserService<T extends User> implements UserDetailsService {
@Autowired
UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
User user = userDao.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用戶不存在");
}
ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>(1);
if (StrUtil.isNotBlank(user.getRoles())) {
String[] roles = user.getRoles().split(",");
for (String role : roles) {
if (!StrUtil.isBlank(role)) {
authorities.add(new SimpleGrantedAuthority("ROLE_"+role.trim()));
}
}
}
log.info("前端用戶名" + username + "==" + user.getPassword());
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), authorities);
} catch (UsernameNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
import com.espringsecurity.utils.MD5Util;
/**
* @author liwen406
* @Title: PasswordEncoder
* @Description:
* @date 2019/5/4 / 18:56
*/
public class PasswordEncoder implements org.springframework.security.crypto.password.PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return MD5Util.encode((String) rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {//user Details Service驗證
return encodedPassword.equals(MD5Util.encode((String) rawPassword));
}
}
package com.espringsecurity.utils;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author liwen406
* @Title: MD5Util
* @Description:
* @date 2019/5/4 / 18:56
*/
public class MD5Util {
public static final int time = 5;
public static final String SALT = "springsecurity";
/**
* 密碼加密方法
*
* @param password
* @return
*/
public static String encode(String password) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 algorithm not available. Fatal (should be in the JDK).");
}
try {
for (int i = 0; i < time; i++) {
byte[] bytes = digest.digest((password + SALT).getBytes("UTF-8"));
password = String.format("%032x", new BigInteger(1, bytes));
}
return password;
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 encoding not available. Fatal (should be in the JDK).");
}
}
public static void main(String[] args) {
System.out.println(MD5Util.encode("123456"));
}
}
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8">
<title>SpringBoot 整合 SpringSecurity</title>
</head>
<body>
<h3 align="center">SpringBoot 整合 SpringSecurity 實現登錄、授權案例</h3>
<div sec:authorize="!isAuthenticated()">
<h5 align="center">游客您好,<a th:href="@{/login}">請登錄</a></h5>
</div>
<div sec:authorize="isAuthenticated()">
<h5><span sec:authentication="name"></span>,您擁有的角色:<span sec:authentication="principal.authorities"></span></h5>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注銷"/>
</form>
</div>
<hr>
<ul>
<div sec:authorize="hasRole('VIP1')">
<li><a th:href="@{/level1}">VIP1,可以訪問</a></li>
</div>
<div sec:authorize="hasRole('VIP2')">
<li><a th:href="@{/level2}">VIP2,可以訪問</a></li>
</div>
<div sec:authorize="hasRole('VIP3')">
<li><a th:href="@{/level3}">VIP3,可以訪問</a></li>
</div>
</ul>
</body>
</html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>美麗的開始</title>
</head>
<body>
<h3 align="center">我們要加油學習登錄頁面</h3>
<hr>
<form th:action="@{/login}" method="post" >
用戶名:<input type="text" name="username"><br>
密碼:<input type="password" name="passowrd"><br>
<input type="checkbox" name="remember"> 記住我<br>
<input type="submit" value="登錄">
</form>
</body>
</html>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。