springboot2.1.4与security5用户认证学习笔记
1、学习这个用了4天终于弄出来
2、刚调试成功做个笔记
创新互联公司主要从事成都做网站、成都网站制作、成都外贸网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务孝昌,10余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792
pom.xml文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
com.eSpringSecurity
demo
0.0.1-SNAPSHOT
demo
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-thymeleaf
org.thymeleaf.extras
thymeleaf-extras-springsecurity5
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
MySQL
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.security
spring-security-test
test
com.alibaba
druid
1.1.9
log4j
log4j
1.2.17
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.10
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
org.webjars
bootstrap
4.3.1
org.webjars.bower
jquery
3.3.1
org.apache.commons
commons-lang3
3.8.1
cn.hutool
hutool-all
4.5.7
org.springframework.boot
spring-boot-maven-plugin
application.properties
#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
application.yml
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.properties
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
config
DruidConfig
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 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 initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
MyBatisConfig
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;
}
}
MyPasswordEncoder
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());
}
}
WebMvcConfig
/**
* @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/");
}
}
WebSecurityConfig
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 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());
}
}
controller
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";
}
}
dao
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);
}
pojo
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;
}
service
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 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 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;
}
}
PasswordEncoder
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));
}
}
MD5Util
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
index.html
SpringBoot 整合 SpringSecurity
SpringBoot 整合 SpringSecurity 实现登录、授权案例
游客您好,请登录
,您拥有的角色:
login.html
美丽的开始
我们要加油学习登录页面
当前题目:springboot2.1.4与security5用户认证学习笔记
URL链接:http://lswzjz.com/article/pgjggp.html