springsecurity登录认证授权示例

springsecurity

简介
Spring Security 是 Spring 家族中的一个安全管理框架。相比与另外一个安全框架Shiro,它提供了更丰富的功能,社区资源也比Shiro丰富。

​ 一般来说中大型的项目都是使用SpringSecurity 来做安全框架。小项目有Shiro的比较多,因为相比与SpringSecurity,Shiro的上手更加的简单。

​ 一般Web应用的需要进行认证和授权。

​ 认证:验证当前访问系统的是不是本系统的用户,并且要确认具体是哪个用户

​ 授权:经过认证后判断当前用户是否有权限进行某个操作

​ 而认证和授权也是SpringSecurity作为安全框架的核心功能。

项目结构

在这里插入图片描述

效果试看

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

所需依赖pom.xml文件

记得需要mybatis-puls和mybatis都需要,在连表查询的时候,需要用到mybatis

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.11</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.junwei</groupId>
    <artifactId>springboot01_15</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot01_15</name>
    <description>springboot01_15</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

yaml文件

连接数据库哦,这里端口号设为8080

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: 密码
  thymeleaf:
    cache: false
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
  port: 8080

数据库中建表两张t_authority和t_customer

创建t_customer表

-- ----------------------------
-- Table structure for t_customer
-- ----------------------------
DROP TABLE IF EXISTS `t_customer`;
CREATE TABLE `t_customer` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `valid` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- ----------------------------
-- Records of t_customer
-- ----------------------------
INSERT INTO `t_customer` VALUES ('1', 'wangwu', '$2a$10$Nq3SdSxpS2h5.fL8NMm5uuV58rInFLSgZHaWQ3bDQxrcD4TdwrY.i', '1');
INSERT INTO `t_customer` VALUES ('2', 'heliu', '$2a$10$ek6vYfDFIspenmjWlqF7BeGJpbmMWHWIfOUDKL71xxIjmVSj/clpa', '1');

创建t_authority表

-- ----------------------------
-- Table structure for t_authority
-- ----------------------------
DROP TABLE IF EXISTS `t_authority`;
CREATE TABLE `t_authority` (
  `id` int NOT NULL AUTO_INCREMENT,
  `cid` int DEFAULT NULL,
  `authority` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- ----------------------------
-- Records of t_authority
-- ----------------------------
INSERT INTO `t_authority` VALUES ('1', '1', 'ROLE_common');
INSERT INTO `t_authority` VALUES ('2', '2', 'ROLE_vip');

config

mySecurity

@Configuration
public class mySecurity extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.inMemoryAuthentication().passwordEncoder(encoder).withUser("zhangsan").password(encoder.encode("123456")).roles("common").and()
                .withUser("lisi").password(encoder.encode("123321")).roles("vip");
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
                     http.authorizeRequests()
                    .antMatchers("/").permitAll().antMatchers("/css/**").permitAll().antMatchers("/js/**").permitAll().antMatchers("/img/**").permitAll()
                    .antMatchers("/detail/common/**").hasRole("common").
                    antMatchers("/detail/vip/**").hasRole("vip")
                             .anyRequest().authenticated()
                             .and().formLogin()
                    .loginPage("/toLogin").permitAll().usernameParameter("username").passwordParameter("password")
                    .defaultSuccessUrl("/").failureUrl("/toLogin?error");
                     http.logout().logoutUrl("/logout").logoutSuccessUrl("/toLogin");
    }
}

controller

FilmController

@Controller
public class FilmController {
    @GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/detail/{type}/{path}")
    public String toDetail(@PathVariable("type") String type, @PathVariable("path") String path) {
        return "detail/" + type + "/" + path;//子文件夹中
    }

    // 向用户登录页面跳转
   // @GetMapping("/userLogin")
    //public String toLoginPage() {
      //  return "login/login";
    //}
    @GetMapping("/toLogin")
    public String login(){
        return "login";
    }
}

CustomerDao

写连表SQL语句了,这里要十分注意

@Mapper
public interface CustomerDao extends BaseMapper<Customer> {
    @Select("select a.id,a.cid,a.authority from t_authority a,t_customer c where c.id=a.cid and c.username=#{username}")
    //select t_authority.id,t_authority.cid,t_authority.authority from t_authority,t_customer where t_customer.id=t_authority.cid and t_customer.username=#{username}
    List<Authority> findUserAuthorities(String username);
}

model

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_authority")
public class Authority {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private Integer cid;
    private String authority;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_customer")
public class Customer {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private Integer valid;
}

UserDetailsServiceImpl

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private CustomerDao customerDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
             QueryWrapper<Customer> wrapper=new QueryWrapper<>();
             wrapper.eq("username",username);
        Customer customer = customerDao.selectOne(wrapper);
        List<Authority> list = customerDao.findUserAuthorities(username);
        List<SimpleGrantedAuthority> list_author = new ArrayList<>();
        for (Authority au : list) {
            list_author.add(new SimpleGrantedAuthority(au.getAuthority()));
        }
        if(customer!=null) {
            UserDetails user = new User(customer.getUsername(), customer.getPassword(), list_author);
            return user;
        }else{
            throw new UsernameNotFoundException("查找不到用户");
        }
    }
}

以下都是templates里内容

common.html

<th:block th:fragment="bootstrap">
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        p{
            font-size: 16px;
        }
    </style>
</th:block>

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <th:block th:insert="~{common :: bootstrap}"></th:block>
</head>
<body>
<div class="container">
    <h1 align="center">欢迎进入电影网站首页</h1>
    <div sec:authorize="isAnonymous()">
        <h2 align="center">游客您好,如果想查看电影<a th:href="@{/toLogin}">请登录</a></h2>
    </div>
    <div sec:authorize="isAuthenticated()">
        <h2 align="center"><span sec:authentication="name" style="color: #007bff"></span>您好,您的用户权限为<span
                sec:authentication="principal.authorities" style="color:darkkhaki"></span>,您有权观看以下电影</h2>
        <form th:action="@{/logout}" method="post">
            <input th:type="submit" class="btn btn-warning" th:value="注销"/>
        </form>
    </div>
    <hr>
    <div sec:authorize="hasRole('common')">
        <h3>普通电影</h3>
        <ul>
            <li><a th:href="@{/detail/common/1}">飞驰人生</a></li>
            <li><a th:href="@{/detail/common/2}">夏洛特烦恼</a></li>
        </ul>
    </div>
    <div sec:authorize="hasAuthority('ROLE_vip')">
        <h3>VIP专享</h3>
        <ul>
            <li><a th:href="@{/detail/vip/1}">速度与激情</a></li>
            <li><a th:href="@{/detail/vip/2}">猩球崛起</a></li>
        </ul>
    </div>
</div>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>登陆页面</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<style>
    body {
        background-color: #f5f5f5;
    }

    .login-container {
        background-color: #fff;
        border-radius: 10px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
        margin: 100px auto;
        max-width: 500px;
        padding: 40px;
    }

    h2 {
        color: #333;
        font-size: 28px;
        margin-bottom: 30px;
        text-align: center;
    }

    form {
        display: flex;
        flex-direction: column;
    }

    label {
        color: #666;
        font-size: 18px;
        margin-bottom: 20px;
    }

    input[type="text"],
    input[type="password"] {
        background-color: #f5f5f5;
        border: none;
        border-radius: 5px;
        font-size: 16px;
        padding: 12px;
        margin-bottom: 20px;
    }

    button[type="submit"] {
        background-color: skyblue;
        border: none;
        border-radius: 5px;
        color: #fff;
        cursor: pointer;
        font-size: 18px;
        padding: 14px;
        transition: background-color 0.3s ease;
    }

    button[type="submit"]:hover {
        background-color: lightblue;
    }
</style>
<body>
<div class="login-container">
    <h2>欢迎登录</h2>
    <form th:action="@{/toLogin}" th:method="post">
        <h3 th:if="${param.error}" style="color:red" align="center">账号或密码错误</h3>
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" placeholder="请输入用户名" required>
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" placeholder="请输入密码" required>
        <button type="submit">登录</button>
    </form>
</div>
</body>
<script>
    var form = document.querySelector('form');
    form.addEventListener('submit', function(event) {
        var username = document.getElementById('username');
        var password = document.getElementById('password');
        if (username.value === '' || password.value === '') {
            event.preventDefault();
            alert('用户名和密码不能为空!');
        }
    });
</script>
</html>

common文件夹下
1

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
	<title>影片详情</title>
	<th:block th:insert="~{common :: bootstrap}"></th:block>
</head>
<body>
	<div class="container">

	<h1>飞驰人生</h1>
	<p>简介:曾经在赛车界叱咤风云、如今却只能经营炒饭大排档的赛车手张驰(沈腾饰)决定重返车坛挑战年轻一代的天才。
		然而没钱没车没队友,甚至驾照都得重新考,这场笑料百出不断被打脸的复出之路,还有更多哭笑不得的窘境在等待着这位过气车神……
	</p>
		<a th:href="@{/}" class="btn btn-warning">返回</a>
	</div>
</body>
</html>

2

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>影片详情</title>
    <th:block th:insert="~{common :: bootstrap}"></th:block>
</head>
<body>
<div class="container">
    <h1>夏洛特烦恼</h1>
    <p>简介:《夏洛特烦恼》是开心麻花2012年首度推出的话剧,由闫非和彭大魔联合编剧、执导。
        2013、2014、2015年仍在上演。该作讲述了一个普通人在穿越重回到高中校园并实现了种种梦想的不可思议的经历……</p>
    <a th:href="@{/}" class="btn btn-warning">返回</a>
</div>
</body>
</html>

vip下
1

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>影片详情</title>
    <th:block th:insert="~{common :: bootstrap}"></th:block>
</head>
<body>
<div class="container">

    <h1>速度与激情</h1>
    <p>简介:《速度与激情》是罗伯·科恩等执导,于2001年至2017年范·迪塞尔、保罗·沃克(已故)、
        乔丹娜·布鲁斯特、米歇尔·罗德里格兹等主演的赛车题材的动作犯罪类电影,截至2018年,一共拍了八部。之后两部续集正式定档,
        《速度与激情9》和《速度与激情10》分别于2020年4月10日和2021年4月2日上映……</p>
    <a th:href="@{/}" class="btn btn-warning">返回</a>
</div>
</body>
</html>

2

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>影片详情</title>
    <th:block th:insert="~{common :: bootstrap}"></th:block>
</head>
<body>
<div class="container">
    <h1>猩球崛起</h1>
    <p>简介:《猩球崛起》是科幻片《人猿星球》的前传,由鲁伯特·瓦耶特执导,詹姆斯·弗兰科,汤姆·费尔顿,
        芙蕾达·平托,布莱恩·考克斯等主演。剧情主要讲述人猿进化为高级智慧生物、进而攻占地球之前的种种际遇,主题是带有警世性质的——人类疯狂的野心所产生的恶果。
        影片获得了第39届安妮奖最佳真人电影角色动画奖等奖项,同时获得了奥斯卡最佳特效奖提名,但很遗憾,并没有获奖……</p>
    <a th:href="@{/}" class="btn btn-warning">返回</a>
</div>
</body>
</html>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程初学者01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值