在Spring Boot中整合Spring Security并自定义验证代码

最终效果

1、实现页面访问权限限制
2、用户角色区分,并按照角色区分页面权限
3、实现在数据库中存储用户信息以及角色信息
4、自定义验证代码

效果如下:
1、免验证页面
这里写图片描述
2、登陆页面
在用户未登录时,访问任意有权限要求的页面都会自动跳转到登陆页面。
这里写图片描述
3、需登陆才能查看的页面
用户登陆后,可以正常访问页面资源,同时可以正确显示用户登录名:
这里写图片描述
4、用户有角色区分,可以指定部分页面只允许有相应用户角色的人使用
4.1、只有ADMIN觉得用户才能查看的页面(权限不足)
这里写图片描述
4.2、只有ADMIN觉得用户才能查看的页面(权限满足)
这里写图片描述

以下具体说明实现步骤。

代码实现

MAVEN引入依赖

在pom.xml中引入spring security依赖

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

配置Spring Security

在Spring中,配置和使用Spring Security,在不需要修改太多流程细节的情况下仅需声明好拦截规则,同时自定义验证过程中的主要实现接口(用户信息UserDetails,用户信息获取服务UserDetailsService,验证工具AuthenticationProvider)即可。其余的流程将由Spring自动接管,非常方便。

启动配置

在项目包下添加WebSecurityConfigurerAdapter 的具体实现类,实现Spring Security的启动配置
代码如下:

@Configurable
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//允许进入页面方法前检验
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   

	@Autowired
	private MyAuthenticationProvider provider;//自定义验证
	@Autowired
	private UserDetailsService userDetailsService;//自定义用户服务
	@Autowired
	public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
   
	}
	
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
   
		http.authorizeRequests()
		
		.antMatchers(StaticParams.PATHREGX.NOAUTH, 
				StaticParams.PATHREGX.CSS,StaticParams.PATHREGX.JS,StaticParams.PATHREGX.IMG).permitAll()//无需访问权限
		
		.antMatchers(StaticParams.PATHREGX.AUTHADMIN).hasAuthority(StaticParams.USERROLE.ROLE_ADMIN)//admin角色访问权限
		
		.antMatchers(StaticParams.PATHREGX.AUTHUSER).hasAuthority(StaticParams.USERROLE.ROLE_USER)//user角色访问权限
		
		.anyRequest()//all others request authentication
		.authenticated()
		.and()
		.formLogin().loginPage("/login").permitAll()
		.and()
		.
  • 14
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 78
    评论
评论 78
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值