SpringBoot攻略十二、spring security集成

本文详细介绍了如何在SpringBoot应用中集成Spring Security,包括添加依赖、配置WebSecurityConfig、设置登录处理类及控制器。通过@EnableWebSecurity和@EnableGlobalAuthentication注解理解其工作原理,以及核心过滤器springSecurityFilterChain的作用。同时提醒读者注意,启用@EnableWebMvc会导致application.properties配置失效。
摘要由CSDN通过智能技术生成

上一篇:【SpringBoot攻略十一、自定义ISqlInjector,添加updateAllColumnById通用方法】

pom.xml添加依赖

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

主要配置类WebSecurityConfig

package com.javasgj.springboot.springsecurity;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

/**
 * 参考【认证、授权攻略三:spring security】
 * 
 * @EnableWebSecurity:开启spring security功能;
 * 		debug: 是否开启debug模式,默认为false;
 */
@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private DataSource dataSource;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		
		// 类似<security:authentication-manager>
		// 测试,用户保存在内存中
		/*auth
			.inMemoryAuthentication()
				.withUser("admin").password("{noop}123").roles("USER");	// USER自动加ROLE_前缀*/
		
		// 数据库加载用户
		auth
			//.eraseCredentials(false)						// 是否清空凭证即密码
			.userDetailsService(jdbcDaoImpl())				// 指定获取用户信息的userDetailsService
			.passwordEncoder(bCryptPasswordEncoder());		// 设置加密方式
		
		// 缓存用户信息,可以参考maven项目SSM的spring-security.xml中的配置
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		
		// 用于Web静态资源的权限控制,忽略静态资源
		web.ignoring().antMatchers("/static/**");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		// 类似<security:http>
		http
			.authorizeRequests()
				.antMatchers("/error1.jsp", "/accessDeny.jsp").permitAll()		// 匹配页面,不需要认证就可以访问
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值