当前位置:   article > 正文

spring boot+spring security +mybatis_springboot+springsecurity+mybatis

springboot+springsecurity+mybatis

流程不写了 自己spring官网学去 我也是没人嘻嘻嘻嘻~~~

话不多说直接发代码

工程目录

application.properties

  1. spring.datasource.url=jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf-8
  2. spring.datasource.username=root
  3. spring.datasource.password=
  4. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  5. logging.level.org.springframework.security=INFO
  6. spring.thymeleaf.cache=false
  7. #打印sql,方便调试
  8. mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

 

domain

  1. package com.securitydemo.security.domain;
  2. public class Msg {
  3. private String title;
  4. private String content;
  5. private String etraInfo;
  6. public Msg(String title, String content, String etraInfo) {
  7. super();
  8. this.title = title;
  9. this.content = content;
  10. this.etraInfo = etraInfo;
  11. }
  12. public String getTitle() {
  13. return title;
  14. }
  15. public void setTitle(String title) {
  16. this.title = title;
  17. }
  18. public String getContent() {
  19. return content;
  20. }
  21. public void setContent(String content) {
  22. this.content = content;
  23. }
  24. public String getEtraInfo() {
  25. return etraInfo;
  26. }
  27. public void setEtraInfo(String etraInfo) {
  28. this.etraInfo = etraInfo;
  29. }
  30. }

 

  1. package com.securitydemo.security.domain;
  2. import javax.persistence.Entity;
  3. import javax.persistence.GeneratedValue;
  4. import javax.persistence.Id;
  5. public class SysRole {
  6. private Long id;
  7. private Long userId;
  8. private String name;
  9. public Long getId() {
  10. return id;
  11. }
  12. public void setId(Long id) {
  13. this.id = id;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. public void setUserId(Long userId) {
  22. this.userId = userId;
  23. }
  24. public Long getUserId() {
  25. return userId;
  26. }
  27. }

 

 

  1. package com.securitydemo.security.domain;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.List;
  5. import javax.persistence.CascadeType;
  6. import javax.persistence.Entity;
  7. import javax.persistence.FetchType;
  8. import javax.persistence.GeneratedValue;
  9. import javax.persistence.Id;
  10. import javax.persistence.ManyToMany;
  11. import org.springframework.security.core.GrantedAuthority;
  12. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  13. import org.springframework.security.core.userdetails.UserDetails;
  14. public class SysUser implements UserDetails { //1
  15. private static final long serialVersionUID = 1L;
  16. private Long id;
  17. private String username;
  18. private String password;
  19. private List<SysRole> roles;
  20. /**
  21. * 重写getAuthorities()方法
  22. * 将用户角色作为权限
  23. *
  24. * @return
  25. */
  26. @Override
  27. public Collection<? extends GrantedAuthority> getAuthorities() {
  28. List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
  29. List<SysRole> roles = this.getRoles();
  30. for (SysRole role : roles) {
  31. auths.add(new SimpleGrantedAuthority(role.getName()));
  32. }
  33. return auths;
  34. }
  35. @Override
  36. public boolean isAccountNonExpired() {
  37. return true;
  38. }
  39. @Override
  40. public boolean isAccountNonLocked() {
  41. return true;
  42. }
  43. @Override
  44. public boolean isCredentialsNonExpired() {
  45. return true;
  46. }
  47. @Override
  48. public boolean isEnabled() {
  49. return true;
  50. }
  51. public Long getId() {
  52. return id;
  53. }
  54. public void setId(Long id) {
  55. this.id = id;
  56. }
  57. public String getUsername() {
  58. return username;
  59. }
  60. public void setUsername(String username) {
  61. this.username = username;
  62. }
  63. public String getPassword() {
  64. return password;
  65. }
  66. public void setPassword(String password) {
  67. this.password = password;
  68. }
  69. public List<SysRole> getRoles() {
  70. return roles;
  71. }
  72. public void setRoles(List<SysRole> roles) {
  73. this.roles = roles;
  74. }
  75. }

service 层 获取用户信息和角色信息

  1. package com.securitydemo.security.service;
  2. import com.securitydemo.security.domain.SysRole;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.apache.ibatis.annotations.Select;
  5. import java.util.List;
  6. /**
  7. * @author Micky
  8. * @Title: UserRoleMapper
  9. * @ProjectName security
  10. * @Description:
  11. * @date 2018/7/20下午6:16
  12. */
  13. @Mapper
  14. public interface UserRoleMapper {
  15. @Select("select * from sys_role where userId=#{id}")
  16. List<SysRole> getRoleByUser(Long id);
  17. }
  1. package com.securitydemo.security.service;
  2. import com.securitydemo.security.domain.SysUser;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.apache.ibatis.annotations.Select;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * @author Micky
  8. * @Title: SysUserMapper
  9. * @ProjectName security
  10. * @Description:
  11. * @date 2018/7/20下午4:36
  12. */
  13. @Mapper
  14. @Component
  15. public interface SysUserMapper {
  16. @Select("select * from sys_user where username=#{username}")
  17. SysUser findByUsername(String username);
  18. }

自定义实现UserDetailsService 接口

  1. package com.securitydemo.security.security;
  2. import com.securitydemo.security.domain.SysRole;
  3. import com.securitydemo.security.domain.SysUser;
  4. import com.securitydemo.security.service.SysUserMapper;
  5. import com.securitydemo.security.service.UserRoleMapper;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  8. import org.springframework.security.core.userdetails.UserDetails;
  9. import org.springframework.security.core.userdetails.UserDetailsService;
  10. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. /**
  14. * @author Micky
  15. * @Title: CustomUserService
  16. * @ProjectName security
  17. * @Description: 实现自定义UserDetailsService接口
  18. * @date 2018/7/20下午3:26
  19. */
  20. public class CustomUserService implements UserDetailsService {
  21. @Autowired
  22. private SysUserMapper sysUserRepository;
  23. @Autowired
  24. private UserRoleMapper userRoleService;
  25. @Override
  26. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  27. SysUser user = sysUserRepository.findByUsername(username);
  28. if(user == null){
  29. throw new UsernameNotFoundException("用户名不存在");
  30. }
  31. List<SimpleGrantedAuthority> authorities = new ArrayList<>();
  32. //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
  33. List<SysRole> roles = userRoleService.getRoleByUser(user.getId());
  34. for(SysRole role:roles)
  35. {
  36. authorities.add(new SimpleGrantedAuthority(role.getName()));
  37. System.out.println(role.getName());
  38. }
  39. return new org.springframework.security.core.userdetails.User(user.getUsername(),
  40. user.getPassword(), authorities);
  41. }

配置confing

  1. package com.securitydemo.security.cofing;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  4. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  6. /**
  7. * @author Micky
  8. * @Title: WebMvcConfig
  9. * @ProjectName security
  10. * @Description:
  11. * @date 2018/7/20下午4:02
  12. */
  13. @EnableWebSecurity
  14. @Configuration
  15. public class WebMvcConfig extends WebMvcConfigurerAdapter {
  16. /**
  17. * 访问login 跳转到login.html页面
  18. *
  19. * @param registry
  20. */
  21. @Override
  22. public void addViewControllers(ViewControllerRegistry registry) {
  23. registry.addViewController("/login").setViewName("login");
  24. }
  25. }
  1. package com.securitydemo.security.cofing;
  2. import com.securitydemo.security.security.CustomUserService;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  7. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  9. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  10. import org.springframework.security.core.userdetails.UserDetailsService;
  11. /**
  12. * @author Micky
  13. * @Title: WebSecurityConfig
  14. * @ProjectName security
  15. * @Description:
  16. * @date 2018/7/20下午4:07
  17. */
  18. @Configuration
  19. @EnableWebSecurity
  20. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  21. /**
  22. * 注册CustomUserService的bean
  23. *
  24. * @return
  25. */
  26. @Bean
  27. UserDetailsService customUserService() { //2
  28. return new CustomUserService();
  29. }
  30. /**
  31. * 添加我们自定义的user UserDetails
  32. *
  33. * @param auth
  34. * @throws Exception
  35. */
  36. @Override
  37. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  38. auth.userDetailsService(customUserService()); //3
  39. }
  40. /**
  41. * @param http
  42. * @throws Exception
  43. */
  44. @Override
  45. protected void configure(HttpSecurity http) throws Exception {
  46. http.authorizeRequests()
  47. .anyRequest().authenticated() //4 所有请求必须要登录后才能认证
  48. .and()
  49. .formLogin()
  50. .loginPage("/login")
  51. .failureUrl("/login?error")//登录失败访问的页面
  52. .permitAll() //5 定制登录页面行为登录页面可以任意访问
  53. .and()
  54. .logout().permitAll() //6 注销可以任意访问
  55. .and().formLogin();
  56. http.csrf().disable();
  57. }
  58. @Override
  59. public void configure(WebSecurity web) throws Exception {
  60. super.configure(web);
  61. web.ignoring().antMatchers("/css/**", "/css/**", "/images/**");//静态资源访问
  62. }
  63. }

 

controller层

  1. package com.securitydemo.security.controller;
  2. import com.securitydemo.security.domain.Msg;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. /**
  7. * @author Micky
  8. * @Title: HomeController
  9. * @ProjectName security
  10. * @Description:
  11. * @date 2018/7/20下午4:22
  12. */
  13. @Controller
  14. public class HomeController {
  15. @RequestMapping("/")
  16. public String index(Model model) {
  17. Msg msg = new Msg("测试标题", "测试内容", "额外信息,只对管理员显示");
  18. model.addAttribute("msg", msg);
  19. return "home";
  20. }
  21. }

 

前端页面  thymeleaf为我们提供了spring security 的标签支持

通过  sec:authentication="name" 获取当前用户名

sec:authorize="hasRole('ROLE_USER')" 意味着只能是ROLE_USER才可以显示标签内容

sec:authorize="hasRole('ROLE_ADMIN')意味着只能是ROLE_ADMIN才可以显示标签内容

注销路径默认是/logout 必须要post 提交

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta content="text/html;charset=UTF-8"/>
  5. <title>登录页面</title>
  6. <link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
  7. <style type="text/css">
  8. body {
  9. padding-top: 50px;
  10. }
  11. .starter-template {
  12. padding: 40px 15px;
  13. text-align: center;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <nav class="navbar navbar-inverse navbar-fixed-top">
  19. <div class="container">
  20. <div class="navbar-header">
  21. <a class="navbar-brand" href="#">Spring Security演示</a>
  22. </div>
  23. <div id="navbar" class="collapse navbar-collapse">
  24. <ul class="nav navbar-nav">
  25. <li><a th:href="@{/}"> 首页 </a></li>
  26. </ul>
  27. </div><!--/.nav-collapse -->
  28. </div>
  29. </nav>
  30. <div class="container">
  31. <div class="starter-template">
  32. <p th:if="${param.logout}" class="bg-warning">已成功注销</p><!-- 1 -->
  33. <p th:if="${param.error}" class="bg-danger">有错误,请重试</p> <!-- 2 -->
  34. <h2>使用账号密码登录</h2>
  35. <form name="form" th:action="@{/login}" action="/login" method="POST"> <!-- 3 -->
  36. <div class="form-group">
  37. <label for="username">账号</label>
  38. <input type="text" class="form-control" name="username" value="" placeholder="账号" />
  39. </div>
  40. <div class="form-group">
  41. <label for="password">密码</label>
  42. <input type="password" class="form-control" name="password" placeholder="密码" />
  43. </div>
  44. <input type="submit" id="login" value="Login" class="btn btn-primary" />
  45. </form>
  46. </div>
  47. </div>
  48. </body>
  49. </html>
  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org"
  3. xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"><!-- 1 -->
  4. <head>
  5. <meta content="text/html;charset=UTF-8"/>
  6. <title sec:authentication="name"></title> <!-- 2 -->
  7. <link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
  8. <style type="text/css">
  9. body {
  10. padding-top: 50px;
  11. }
  12. .starter-template {
  13. padding: 40px 15px;
  14. text-align: center;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <nav class="navbar navbar-inverse navbar-fixed-top">
  20. <div class="container">
  21. <div class="navbar-header">
  22. <a class="navbar-brand" href="#">Spring Security演示</a>
  23. </div>
  24. <div id="navbar" class="collapse navbar-collapse">
  25. <ul class="nav navbar-nav">
  26. <li><a th:href="@{/}"> 首页 </a></li>
  27. </ul>
  28. </div><!--/.nav-collapse -->
  29. </div>
  30. </nav>
  31. <div class="container">
  32. <div class="starter-template">
  33. <h1 th:text="${msg.title}"></h1>
  34. <p class="bg-primary" th:text="${msg.content}"></p>
  35. <div sec:authorize="hasRole('ROLE_ADMIN')"> <!-- 3 -->
  36. <p class="bg-info" th:text="${msg.etraInfo}"></p>
  37. </div>
  38. <div sec:authorize="hasRole('ROLE_USER')"> <!-- 4-->
  39. <p class="bg-info">无更多信息显示</p>
  40. </div>
  41. <form th:action="@{/logout}" method="post">
  42. <input type="submit" class="btn btn-primary" value="注销"/><!-- 5 -->
  43. </form>
  44. </div>
  45. </div>
  46. </body>
  47. </html>

运行

 

 

 

 

 

 

 

 

 

 

 

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/875393
推荐阅读
相关标签
  

闽ICP备14008679号