当前位置:   article > 正文

学习security(二)_savesecurity(sysuser)

savesecurity(sysuser)

一.secrity的自定义登录注册

1.实现用户注册后,输入密码后登录到主页,获取用户角色,用户名等。点击其他界面,权限不足报错,权限通过则请求成功。效果如下:
在这里插入图片描述

2.导入依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--视图解析-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--引入thymeleaf与Spring Security整合的依赖-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>
        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

3.配置application.properties

server.port=8015
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security-demo?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
mybatis.configuration.map-underscore-to-camel-case=true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4.创建用户类SysUser

public class SysUser implements Serializable {
    static final long serialVersionUID = 1L;

    private Integer id;

    private String name;

    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

5.创建角色类SysRole

public class SysRole implements Serializable {
    static final long serialVersionUID = 1L;

    private Integer id;

    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

6.Dao
(6.1)SysRoleMapper

@Mapper
public interface SysRoleMapper {
   @Select("select * from sys_role where id = #{id}")
    SysRole selectById(Integer id);

    @Insert("insert into sys_role (name) values (#{name})")
    int saveSysRole(String name);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(6.2)SysUserMapper

@Mapper
public interface SysUserMapper {
   @Select("select * from sys_user where id = #{id}")
    SysUser selectById(Integer id);

    @Select("select * from sys_user where name = #{name}")
    SysUser selectByName(String name);

    @Insert("insert into sys_user (name,password) values (#{name},#{password})")
    int saveSysUser(SysUser sysUser);

    @Select("select * from sys_user where id = #{id}")
    List<SysUser> listByUserId(Integer userId);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

7.service
(7.1)SysRoleService

@Service
public class SysRoleService {
    @Resource
    private SysRoleMapper roleMapper;

    public SysRole selectById(Integer id) {
        return roleMapper.selectById(id);
    }

    public int saveSysRole(String name){
        return roleMapper.saveSysRole(name);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

(7.2)SysUserService

@Service
public class SysUserService {
   @Resource
    private SysUserMapper userMapper;

    public SysUser selectById(Integer id) {
        return userMapper.selectById(id);
    }

    public SysUser selectByName(String name) {
        return userMapper.selectByName(name);
    }
    public List<SysUser> listByUserId(Integer userId) {
        return userMapper.listByUserId(userId);
    }
    public int saveSysUser(SysUser sysUser) {
        encryptPassword(sysUser);
        return userMapper.saveSysUser(sysUser);
    }

    /**
     * 加密密码
     */
    private SysUser encryptPassword(SysUser userEntity){
        String password = userEntity.getPassword();
        password = new BCryptPasswordEncoder().encode(password);
        userEntity.setPassword(password);
        return userEntity;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

8 .controller

@Controller
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;


    @RequestMapping("/")
    public String showHome() {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        logger.info("当前登陆用户:" + name);

        return "home";
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping("login")
    public String showLogin() {
        return "login";
    }

    /**
     * 跳转注册
     * @return
     */
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }
    /**
     * 注册
     * @return
     */
    @RequestMapping("/register")
    public String register(SysUser sysUser, String role, HttpServletRequest request) {
        SysUser user=userService.selectByName(sysUser.getName());
        if (user==null){
            userService.saveSysUser(sysUser);
            roleService.saveSysRole(role);
            request.setAttribute("login","注册成功,请登录!");
            return "login";
        }
//        return "<script>alert(\"账号已存在,请重新注册!\");window.location.href=\"/toRegister\";</script>";
        request.setAttribute("login","账号已存在,请重新注册!");
        return "register";
    }

    @RequestMapping("/admin")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String printAdmin() {
        return "<h2>段位:白银</h2></br><h4>欢迎来到白银试炼场</h2>";
    }

    @RequestMapping("/user")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_USER')")
    public String printUser() {
        return "<h2>段位:青铜</h2></br><h4>欢迎来到青铜试炼场</h2>";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67

9 . 配置SpringSecurity
(9.1)自定义 CustomUserDetailsService ,将用户信息和权限注入进来。它有三个参数,分别是用户名、密码和权限集

@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
   @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        // 从数据库中取出用户信息
        SysUser user = userService.selectByName(username);

        // 判断用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 添加权限
        List<SysUser> user2 = userService.listByUserId(user.getId());
        for (SysUser users : user2) {
            SysRole role = roleService.selectById(users.getId());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        // 返回UserDetails实现类
        return new User(user.getName(), user.getPassword(), authorities);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

(9.2)Spring Security 的配置类WebSecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   @Autowired
    private CustomUserDetailsService userDetailsService;
    
   @Override
   protected void configure(AuthenticationManagerBuilder builder) throws Exception{
       builder.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
   }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/toRegister","/register").permitAll()//允许注册直接使用
                .anyRequest().authenticated()
                .and()
                // 设置登陆页
                .formLogin().loginPage("/login")
                // 设置登陆成功页
                .defaultSuccessUrl("/").permitAll()
                // 自定义登陆用户名和密码参数,默认为username和password
                .and()
                .logout().permitAll();
                http.csrf().disable(); // 关闭CSRF跨域
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置拦截忽略文件夹,可以对静态资源放行
        web.ignoring().antMatchers("/css/**", "/js/**");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

10 .主界面home.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>欢迎来到王者峡谷</h1>
<div sec:authorize="isAuthenticated()">
    <p>已登录</p>
    <p>登录名:<span sec:authentication="name"></span></p>
    <p>当前段位:
        <span sec:authorize="hasRole('ROLE_ADMIN')">不屈白银</span>
        <span sec:authorize="hasRole('ROLE_USER')">倔强青铜</span>
    </p>
    <button onclick="window.location.href='/admin'">白银用户传送门</button>
    <button onclick="window.location.href='/user'">青铜用户传送门</button>
</div>
<p></p>
<button onclick="window.location.href='/logout'">退出登录</button>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

11 . 登录界面login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/jquery-3.2.1.js"></script>
    <script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="starter-template">
        <h2>亲爱的召唤师请登录</h2>
        <form class="form-signin" action="/login" method="post">
            <p id="ifLogin" class="bg-info" th:text=${login}></p>
            <p th:if="${param.logout}" class="bg-warning">已注销</p>
            <p th:if="${param.error}" class="bg-danger">账号密码错误,请重试</p>
            <div class="form-group">
                <label for="username">账号</label>
                <input type="text" id="username" class="form-control" name="username" value="haha" placeholder="账号"/>
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" value="111111" class="form-control" name="password"
                       placeholder="密码"/>
            </div>
            <input type="submit" id="login" value="登录" class="btn btn-primary"/>
            <input type="button" onclick="window.location.href='/toRegister'" value="注册" class="btn btn-info"/>
        </form>
    </div>
</div>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

12 . 注册界面register.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/jquery-3.2.1.js"></script>
    <script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="starter-template">
        <h2>亲爱的召唤师请注册</h2>
        <p class="bg-danger" th:text=${login}></p>
        <form class="form-signin" action="/register" method="post">
            <div class="form-group">
                <label for="username">账号</label>
                <input type="text" id="username" class="form-control" name="name" placeholder="账号"/>
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" class="form-control" name="password" placeholder="密码"/>
            </div>
            <div class="form-group">
                <label>段位</label>
                <select name="role" id="" class="form-control">
                    <option value="ROLE_USER">青铜</option>
                    <option value="ROLE_ADMIN">白银</option>
                </select>
            </div>
            <input type="submit" value="注册" class="btn btn-primary"/>
            <input type="button" onclick="window.location.href='/login'" value="去登录" class="btn btn-info"/>
        </form>
    </div>
</div>
</body>

</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

完成。正在学习中,有错误的地方请大神们指点一下

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号