Spring Boot -- 整合Spring Security

1.引入Spring Security:

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

2.编写Spring Security配置类:

继承WebSecurityConfigurerAdapter ,加上@EnableWebSecurity注解
package com.id0304.security.config;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
}

3.控制请求的访问权限:

1) 授权:用户进入路径会通过身份进行授权

这里我们先定制授权规则,就是对路径加上一层身份,重写WebSecurityConfigurerAdapter的configure(HttpSecurity http)方法,记得传入参数是HttpSecurity类型的这个方法.

	//定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
		//super.configure(http);
        http.authorizeRequests().antMatchers("/").permitAll()	//授权所有
                .antMatchers("/level1/**").hasRole("vip1")		//授权身份为vip1的用户
                .antMatchers("/level2/**").hasRole("vip2")		//授权身份为vip2的用户
                .antMatchers("/level3/**").hasRole("vip3");		//授权身份为vip3的用户

        //开启自动配置的登录功能,如果没有权限,会自动跳转到一个登陆界面(自带).
        http.formLogin();		//若没有开启登录功能,没有权限的用户访问会出现403拒绝访问
        /**
         * springboot自动配置规则:
         * 1./login请求来到登录页
         * 2.重定向到/login?error表示登陆失败
         * 3.   ...
         */
         
		//开启自动配置的注销功能,加上logoutSuccessUrl注销成功返回首页,默认返回登录页
        http.logout().logoutSuccessUrl("/");
        /**
         * springboot自动配置注销规则:自动发送/logout请求实现注销
         * 页面可以提供一个注销表单,请求地址是/logout,但是必须以post方式注销,这是Spring Security的规定
         * 注销成功会清空session
         */
         
		//开启记住密码功能,账号密码会保存在cookie里
        http.rememberMe();
    }

示例页面部分代码(使用了thymeleaf模板):

<h2 align="center">游客您好,<a th:href="@{/login}">请登录</a></h2>
<form th:action="@{/logout}" method="post">
	<input type="submit" value="注销">
</form>
2) 认证:用户登录会被提供一个身份,开放对应权限

重写父类的configure(AuthenticationManagerBuilder auth)方法,这个方法传入的参数是AuthenticationManagerBuilder类型的

	//定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//super.configure(auth);
		//这里我们没有去调用数据库,所以使用静态参数去演示
		//重点是.roles方法传入的身份,可以添加多个用户
        auth.inMemoryAuthentication()
        							.withUser("zhangsan").password("123456").roles("vip1","vip2")
                                    .and()
                                    .withUser("lisi").password("123456").roles("vip3");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值