<h4>场景</h4>

<h4>代码</h4>

springboot+springsecurity+mysql(jpa)实现:

1.pom依赖:

 <!-- security -->
<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> <!--jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

2.application配置:

 spring.thymeleaf.prefix=classpath:/page/

 #mysql连接地址
spring.datasource.url=jdbc:mysql://localhost:3307/springboot_test
#mysql用户名和密码
spring.datasource.username=root
spring.datasource.password=root
#driver驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#show sql
spring.jpa.show-sql=true
# Hibernate ddl auto (create, create-drop, update)
#### hibernate的ddl-auto=update配置表名,数据库的表和列会自动创建(根据Java实体)
spring.jpa.hibernate.ddl-auto=update
# 方言
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

3.连接数据库:db->bean->dao->service

public interface UserDao extends JpaRepository<User, Long>{

    User findByUserName(String userName);
User findByUserNameAndPassword(String userName, String password);
}
@Service
public class UserService {
@Autowired
private UserDao userDao; public User findById(Long id){
return userDao.findOne(id);
} public User findByUserName(String userName){
return userDao.findByUserName(userName);
} public User login(String userName, String password){
return userDao.findByUserNameAndPassword(userName, password);
} public List<User> userList(){
return userDao.findAll();
}
}

实体类User

@Entity
@Table(name = "user")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userName;
private String password;
private String pwdBak;
private String role; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} @Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> auths = new ArrayList<>();
auths.add(new SimpleGrantedAuthority(this.getRole()));
return auths;
} public String getPassword() {
return password;
} @Override
public String getUsername() {
return this.userName;
} @Override
public boolean isAccountNonExpired() {
return true;
} @Override
public boolean isAccountNonLocked() {
return true;
} @Override
public boolean isCredentialsNonExpired() {
return true;
} @Override
public boolean isEnabled() {
return true;
} public void setPassword(String password) {
this.password = password;
} public String getPwdBak() {
return pwdBak;
} public void setPwdBak(String pwdBak) {
this.pwdBak = pwdBak;
} public String getRole() {
return role;
} public void setRole(String role) {
this.role = role;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", pwdBak='" + pwdBak + '\'' +
", role='" + role + '\'' +
'}';
}
}

4.websecurity配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启进入Controller之前,检验权限。这个注解配置后,Controller中的@PreAuthorize("hasAnyAuthority('ADMIN')")才会生效
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
private MyUDService myUDService;
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
} @Override
protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.authorizeRequests()
.antMatchers("/", "/login", "/err/*").permitAll() //无需验证权限
.anyRequest().authenticated() //其他地址的访问均需验证权限
.and().formLogin().loginPage("/login").defaultSuccessUrl("/home").permitAll()//指定登录页是"/login" //登录成功后默认跳转到"/home"
.and().logout().logoutSuccessUrl("/login").permitAll(); //退出登录后的默认url是"/login"
} /**
* 全局配置
* @param builder
* @throws Exception
*/
@Autowired
public void configure(AuthenticationManagerBuilder builder) throws Exception {
builder
.userDetailsService(myUDService)
.passwordEncoder(this.passwordEncoder());
} /**
* 设置用户密码的加密方式:MD5加密
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder pe = new PasswordEncoder() {//自定义密码加密方式
//加密
@Override
public String encode(CharSequence charSequence) {
return MD5Util.encode((String)charSequence);
} //校验密码
@Override
public boolean matches(CharSequence charSequence, String s) {
return MD5Util.encode((String)charSequence).equals(s);
}
};
return pe;
}
}

5.用户权限查询类UserDetailsService:

@Component
public class MyUDService implements UserDetailsService { @Autowired
private UserService userService; @Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userService.findByUserName(s);
if(user == null) {
throw new UsernameNotFoundException("UserName " + s + " not found");
} System.out.println("用户" + s + ":" + user);
return user;
}
}

6.启动类:

@SpringBootApplication
public class Start02App { public static void main(String[] args) {
SpringApplication.run(Start02App.class, args);
} /**
* 自定义异常页
*/
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer(){
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
container.addErrorPages(new ErrorPage(java.lang.Throwable.class,"/error/500"));
container.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN,"/error/403"));
}
};
}
}

7.页面

8.往数据库插入数据(单元测试):

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Start02App.class)
public class UserServiceTest { @Autowired
private UserDao userDao;
@Autowired
private UserService userService; private ObjectMapper objectMapper = new ObjectMapper(); @Test
public void testAll() throws JsonProcessingException { this.saveUser();
this.list(); } private void saveUser() throws JsonProcessingException {
User admin = new User();
admin.setUserName("admin");
admin.setPassword(MD5Util.encode("admin"));
admin.setPwdBak("admin");
admin.setRole("ADMIN");
User adminSave = userDao.save(admin);
for(int i=0;i<=5;i++) {
System.out.println("admin save--->:" + objectMapper.writeValueAsString(adminSave));
User user = new User();
user.setUserName("test"+i);
user.setPassword(MD5Util.encode("user" + i));
user.setPwdBak("user" + i);
user.setRole("USER");
User userSave = userDao.save(user);
System.out.println("user save--->:" + objectMapper.writeValueAsString(userSave));
}
} private void list() throws JsonProcessingException {
List<User> userList = userService.userList();
System.out.println("用户列表:" + objectMapper.writeValueAsString(userList));
} }

查看数据库:

<h4>效果</h4>

启动app类,访问:http://localhost:8080/

测试:

先点击“去主页”或“查看用户列表”,要求输入用户名密码:

使用admin登录,跳转到主页:

返回后,点击去“用户列表”,跳转到403,提示没有权限:

注销后使用普通用户登录,可以跳转到用户列表页面:

测试500页面:

测试404页面:

项目地址:https://github.com/yangzhenlong/mySpringBootDemo/tree/master/springboot11-auth/springboot11-security02FromDB

springboot11-security02FromDB 权限管理(用户信息和角色信息保存在数据库)的更多相关文章

  1. Linux用户和权限——管理用户和用户组的命令

    Linux用户和权限——管理用户和用户组的命令 摘要:本文主要学习了在Linux系统中管理用户和用户组的命令. useradd命令 useradd命令可以用来创建新用户. 基本语法 useradd [ ...

  2. 无责任Windows Azure SDK .NET开发入门篇三[使用Azure AD 管理用户信息]

    三.使用Azure AD管理用户信息 在上一章我们采用OpenID的方案和Azure AD交互进行身份验证,本章节我们继续了解如何在Azure AD中创建用户,列出用户信息,修改用户信息和删除用户信息 ...

  3. ThinkPHP 3 的CURD管理用户信息 修改和删除

    本节课大纲: 一.ThinkPHP 3 的CURD管理用户信息 http://localhost:8080/thinkphp/index.php/User/index 访问User类的index方法 ...

  4. HDFS权限管理用户指南

    原文地址:http://hadoop.apache.org/docs/r1.0.4/cn/hdfs_permissions_guide.html 概述 用户身份 理解系统的实现 文件系统API变更 S ...

  5. VisualSVN Server仓库迁移到Linux(包含所有版本, 权限,用户信息)

    公司开发服务器从Windows换成CentOS,所以要把原服务都转移到Linux下,MySQL.SMB的迁移都很顺利,但是SVN的转移却遇到了些问题,花费了三天时间,走了不少弯路,现在总算解决了SVN ...

  6. springboot学习笔记:11.springboot+shiro+mysql+mybatis(通用mapper)+freemarker+ztree+layui实现通用的java后台管理系统(权限管理+用户管理+菜单管理)

    一.前言 经过前10篇文章,我们已经可以快速搭建一个springboot的web项目: 今天,我们在上一节基础上继续集成shiro框架,实现一个可以通用的后台管理系统:包括用户管理,角色管理,菜单管理 ...

  7. Linux 用户和用户组管理-用户信息文件

    用户信息文件存在在/etc/passwd中,vi /etc/passwd 其中,有七列以:分隔的信息 第一列表示用户(account),第二列表示密码标志(真正的密码存在在/etc/shadow中), ...

  8. 无责任Windows Azure SDK .NET开发入门篇三[使用Azure AD 管理用户信息--3.4 Edit修改用户信息]

    3.4 Edit修改用户信息 我们用FormCollection简化了表单提交,非常方便的进行用户信息修改. [HttpPost, Authorize] public async Task<Ac ...

  9. Spring Boot教程(四十二)LDAP来管理用户信息(2)

    使用spring-data-ldap的基础用法,定义LDAP中属性与我们Java中定义实体的关系映射以及对应的Repository @Data @Entry(base = "ou=peopl ...

随机推荐

  1. ORACLE报错和解决方案

    ORA-01034: ORACLE not available ORA-27101 出现ORA-01034和ORA-27101的原因是多方面的:主要是oracle当前的服务不可用,shared mem ...

  2. 【洛谷P2704】炮兵阵地

    题目大意:定义一个炮兵会影响该点所在坐标上下左右两个格子的范围,求一个 N*M 的网格里最多可以放多少个炮兵. 题解:发现这个问题有需要记录两个状态,即:上一层的状态和上两层的状态,若直接进行记录,空 ...

  3. 第三十七篇-BottomNavigationVIew底部导航的使用

    效果图: 添加底部导航和viewpaper 设置底部导航在底部 app:layout_constraintBottom_toBottomOf="parent" 新建四个fragme ...

  4. 数据库日志redo和undo

    数据库的ACID属性 Atomicity:原子性,以事物transact为最小单位,事物中的所有操作,要么都执行完,要么都不执行,不存在一部分操作执行,另一部分操作不执行的情况. Consistenc ...

  5. Luogu P3254 圆桌问题

    题目链接 \(Click\) \(Here\) 水题.记得记一下边的流量有没有跑完. #include <bits/stdc++.h> using namespace std; const ...

  6. java 打印乘法口诀表

    package cn.lijun.demo6; public class Test3 { public static void main(String[] args) { for(int j=1;j& ...

  7. 25 个常用的 Linux iptables 规则

    # 1. 删除所有现有规则 iptables -F   # 2. 设置默认的 chain 策略 iptables -P INPUT DROP iptables -P FORWARD DROP ipta ...

  8. Linux如何修改和查询时区时间

    Linux如何修改和查询时区时间 我在日常工作中,最近遇到了在解压源码包的时候,提示时间比较旧,解压安装出现问题.原因是,租用的vps所在时区和自己所需要的时区不一致,于是在网上找了相关资料.并亲自实 ...

  9. gometalinter代码质量检查分析工具(golang)

    GitHub地址:https://github.com/alecthomas/gometalinter gometalinter安装和使用 1.安装 go get github.com/alectho ...

  10. REST_返回形式

    摘录: "Web resources" were first defined on the World Wide Web as documents or files identif ...