SpringBoot整合Spring Secuity

1、SpringBoot整合Spring Secuity

a、导入相关依赖

 		<!--导入thymeleaf与Secuity组合操作的依赖-->
		<!--注意版本与thymeleaf的兼容问题-->
		<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
		<!--导入thymeleaf依赖操作静态页面-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
		<!--导入Secuity依赖,使用Secuity-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

b、插入@EnableWebSecurity到自己的Secuity配置类

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    //定义认证规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasAnyRole("vip1")
                .antMatchers("/level2/**").hasAnyRole("vip2")
                .antMatchers("/level3/**").hasAnyRole("vip3");
        //开启自动配置的登录功能,如果没登陆会跳到此页
        http.formLogin();

        http.logout().logoutSuccessUrl("/");//注销成功跳转到“/”
        
        http.rememberMe();//开启记住我选项
    }

    //定义授权规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("lisi")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("wangwu")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }
}

c、静态页面的配置

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
	  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <!--导入springsecurity的命名空间,这里也要注意版本问题-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
	<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div>

<div sec:authorize="isAuthenticated()">
	<h2><span sec:authentication="name"></span>,您好,您的角色是
	<span sec:authentication="principal.authorities"></span></h2>
	<form th:action="@{/logout}" method="post">
		<input type="submit" value="注销"/>
	</form>
</div>

<hr>
<div sec:authorize="hasRole('vip1')">
	<h3>普通武功秘籍</h3>
	<ul>
		<li><a th:href="@{/level1/1}">罗汉拳</a></li>
		<li><a th:href="@{/level1/2}">武当长拳</a></li>
		<li><a th:href="@{/level1/3}">全真剑法</a></li>
	</ul>
</div>

<div sec:authorize="hasRole('vip2')">
	<h3>高级武功秘籍</h3>
	<ul>
		<li><a th:href="@{/level2/1}">太极拳</a></li>
		<li><a th:href="@{/level2/2}">七伤拳</a></li>
		<li><a th:href="@{/level2/3}">梯云纵</a></li>
	</ul>
</div>

<div sec:authorize="hasRole('vip3')">
	<h3>绝世武功秘籍</h3>
	<ul>
		<li><a th:href="@{/level3/1}">葵花宝典</a></li>
		<li><a th:href="@{/level3/2}">龟派气功</a></li>
		<li><a th:href="@{/level3/3}">独孤九剑</a></li>
	</ul>
</div>



</body>
</html>

d、sec的相关用法集合

sec:authorize="!isAuthenticated()" 未登录

sec:authorize=“isAuthenticated()” 已登录

sec:authorize=“hasRole(‘xxxx’)” 判断设置的用户信息是那个

sec:authentication=“name” 取出用户名

sec:authentication=“principal.authorities” 取出设置的所有授权信息

e、登陆页面的定制

通过读取formLogin方法的参考文档得知,其默认参数如下:

.usernameParameter(&quot;username&quot;) // default is username
.passwordParameter(&quot;password&quot;) // default is password
.loginPage(&quot;/authentication/login&quot;) // default is /login with an HTTP get
.failureUrl(&quot;/authentication/login?failed&quot;) // default is /login?error
.loginProcessingUrl(&quot;/authentication/login/process&quot;); // default is /login
																		// with an HTTP
																				// post

由此可见,如需定制则要声明自定义登录页的用户名,密码的name属性,以及loginPage既处理登录请求的地址设置。具体设置如下

//package com.wyy.springboot.config.MySecurityConfig;
http.formLogin().usernameParameter("user").passwordParameter("pwd")
     .loginPage("/userlogin");

//userlogin请求的具体内容
	@GetMapping("/userlogin")
	public String loginPage() {
		return PREFIX+"login";
	}

记住密码框的实现&自定义

首先简单实现是通过调用rememberMe方法,自定义则需要调用rememberMeParameter方法传入自定义的input框name属性值,具体如下

//package com.wyy.springboot.config.MySecurityConfig;
//简单实现
http.rememberMe();

//自制实现
http.rememberMe().rememberMeParameter("remember");

这里的原理可以点进方法自行参考rememberMe和rememberMeParameter这两个方法的参考文档

前端内容的实现步骤

首先改变欢迎页的登录请求位置

<!--默认是发login-->
<a th:href="@{/login}">请登录</a></h2>	
<!--改为自定义的请求地址-->
<a th:href="@{/userlogin}">请登录</a></h2>

其次编写自定义登陆页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1 align="center">欢迎登陆武林秘籍管理系统</h1>
	<hr>
	<div align="center">
		<form th:action="@{/userlogin}" method="post">
            <!--注意这里的相关name属性要与后端一致-->
			用户名:<input name="user"/><br>
			密码:<input name="pwd"><br/>
			<input type="checkbox" name="remember"> 记住密码
			<input type="submit" value="登陆">
		</form>
	</div>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

祭音丶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值