SpringBoot+SpringSecurity中自定义适配器简单例子

最近闲来无事,熟悉公司的项目框架的时候,发现公司是用的spring boot整合spring security来控制用户登录以及用户角色,权限等。之前只用过apache shiro,对spring security的了解甚少,只知道它提供的功能比shiro更强大,所以写下此文章,记录一下自己对spring security的学习过程。

spring官网上面有这么一段demo,它给我们说明了spring security自定义适配器的部分功能:

package org.springframework.security.samples.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeRequests()
				.antMatchers("/css/**", "/index").permitAll()		
				.antMatchers("/user/**").hasRole("USER")			
				.and()
			.formLogin()
				.loginPage("/login").failureUrl("/login-error");	
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.inMemoryAuthentication()
				.withUser("user").password("password").roles("USER");
	}
}

1. / css / **/ index匹配的请求是完全可访问的

2./ user / **匹配的请求要求用户进行身份验证,并且必须与USER角色相关联

3.使用自定义登录页面和失败URL启用基于表单的身份验证

4.configure方法重写了父类的方法,里面定义了spring security应该忽略或者拦截验证的一些url路径。

5. configureGlobal方法是确定您要如何进行身份验证,上面的demo是在内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值