Spring boot 中使用 spring security

spring security

数据库脚本

/*
Navicat MySQL Data Transfer

Source Server         : work01
Source Server Version : 50716
Source Host           : localhost:3306
Source Database       : spring_boot_chapter12

Target Server Type    : MYSQL
Target Server Version : 50716
File Encoding         : 65001

Date: 2019-06-23 16:25:25
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_role
-- ----------------------------
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `role_name` varchar(255) DEFAULT NULL,
  `note` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_role
-- ----------------------------
INSERT INTO `t_role` VALUES ('1', 'a', '啊');

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `pwd` varchar(255) NOT NULL,
  `available` int(1) DEFAULT '1' COMMENT '1表示可用,0表示不可用',
  `note` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', 'aaa', '$2a$10$J6WSDcck1W5c38yGKz2cYejYVEGykDOJWBS0oh/fNTyQqjGR7SN9y', '1', '密码111');
INSERT INTO `t_user` VALUES ('2', '', '', '1', null);
INSERT INTO `t_user` VALUES ('3', '', '', '1', null);
INSERT INTO `t_user` VALUES ('4', '', '', '1', null);

-- ----------------------------
-- Table structure for t_user_role
-- ----------------------------
DROP TABLE IF EXISTS `t_user_role`;
CREATE TABLE `t_user_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role_id` int(11) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user_role
-- ----------------------------
INSERT INTO `t_user_role` VALUES ('1', '1', '1');

如果使用到密码管理器,数据库中的密码要修改为对应密码管理加密后的密码,否则在认证是原始密码(未经过加密)与加密后的密码无法成功认证(两次加密后的字符串不一样,但是不影响密码的认证)

先创建一个web工程,目录结构如下

welcome.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学习Spring Security</title>
</head>
<body>
	<h1>欢迎学习Spring Security!!</h1>
</body>
</html>
WelcomeController.java
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class WelcomeController {

    @GetMapping("/welcome")
    public String welcome() {
        return "welcome";
    }


}

启动文件中代码如下

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@SpringBootApplication
public class Springboot0623Application extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource = null;
    // 使用用户名称查询密码
    String pwdQuery = " select user_name, pwd, available "
                    + " from t_user where user_name = ?";
    // 使用用户名称查询角色信息
    String roleQuery = " select u.user_name, r.role_name  "
                    + " from t_user u, t_user_role ur, t_role r  "
                      + "where u.id = ur.user_id and r.id = ur.role_id" + " and u.user_name = ?";

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        auth.jdbcAuthentication()
                .passwordEncoder(passwordEncoder)
                .dataSource(dataSource)
                .usersByUsernameQuery(pwdQuery)
                .authoritiesByUsernameQuery(roleQuery);
    }

    public static void main(String[] args) {
        SpringApplication.run(Springboot0623Application.class, args);
    }

}

要访问jsp页面需要添加两个依赖

        <!--jsp-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>7.0.59</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

否则访问时会出现如下情况

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Jun 23 16:39:10 CST 2019

There was an unexpected error (type=Not Found, status=404).

No message available

此时请求http://localhost:8080/welcome时,可以跳转到welcome.jsp页面

使用security认证

在pom文件中加入security的依赖

        <!--security安全认证-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

此时访问http://localhost:8080/welcome时,会跳转到security安全认证默认的登录页面

此时输入数据库中的用户名和密码(密码为没有经过加密的密码)即可访问到welcom.jsp页面

猜你喜欢

转载自blog.csdn.net/qq_43039260/article/details/93386102