springboot整合springSecurity

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
1.引入maven依赖

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.1.RELEASE</version>
</parent>
<!-- 管理依赖 -->
<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>Finchley.M7</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
<dependencies>
	<!-- SpringBoot整合Web组件 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
	</dependency>

	<!-- springboot整合freemarker -->
	<dependency>
		<!-->spring-boot 整合security -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency><groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-freemarker</artifactId>
	</dependency>

</dependencies>
<!-- 注意: 这里必须要添加, 否者各种依赖有问题 -->
<repositories>
	<repository>
		<id>spring-milestones</id>
		<name>Spring Milestones</name>
		<url>https://repo.spring.io/libs-milestone</url>
		<snapshots>
			<enabled>false</enabled>
		</snapshots>
	</repository>
</repositories>
2.修改application.yml
# 配置freemarker

spring:
freemarker:
# 设置模板后缀名
suffix: .ftl
# 设置文档类型
content-type: text/html
# 设置页面编码格式
charset: UTF-8
# 设置页面缓存
cache: false
# 设置ftl文件路径
template-loader-path:
- classpath:/templates

设置静态文件路径,js,css等

mvc:
static-path-pattern: /static/**
3.编写SecurityConfig
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// 用户认证信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	// 设置用户账号信息和权限
	auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("addOrder");
}

// 配置HttpSecurity 拦截资源
protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
}

}
启动项目
There is no PasswordEncoder mapped for the id “null”
原因:升级为Security5.0以上密码支持多中加密方式,回复以前模式

@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
FromLogin
FromLogin以表单形式进行认证
// 配置HttpSecurity 拦截资源
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
}

Security权限控制
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// 用户认证信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	// 设置用户账号信息和权限
	 auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("showOrder","addOrder","updateOrder","deleteOrder");
	 // 添加 useradd账号 只有添加查询和添加订单权限
	 auth.inMemoryAuthentication().withUser("userAdd").password("123456")
		.authorities("showOrder","addOrder");
}

// 配置HttpSecurity 拦截资源
protected void configure(HttpSecurity http) throws Exception {
	// 拦截请求, 权限名称
	http.authorizeRequests()
	.antMatchers("/showOrder").hasAnyAuthority("showOrder")
	.antMatchers("/addOrder").hasAnyAuthority("addOrder")
	.antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
	.antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
	.antMatchers("/**").fullyAuthenticated().and().formLogin();
}

// SpringBoot2.0抛弃了原来的NoOpPasswordEncoder,要求用户保存的密码必须要使用加密算法后存储,在登录验证的时候Security会将获得的密码在进行编码后再和数据库中加密后的密码进行对比
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
	return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}

}

修改403错误页面
403报错权限不足

控制器页面请求跳转

@Controller
public class ErrorController {

@RequestMapping("/error/403")
public String error() {
	return "/error/403";
}

}

自定义WEB 服务器参数
/**

  • 自定义 WEB 服务器参数 可以配置默认错误页面
  • @author 余胜军
  • @version 2018年11月12日
    */
    @Configuration
    public class WebServerAutoConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
    ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, “/error/400”);
    ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, “/error/401”);
    ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, “/error/403”);
    ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, “/error/404”);
    ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, “/error/415”);
    ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, “/error/500”);
    factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
    return factory;
    }
    }

修改fromLogin登陆页面
关闭csdrf、配置loginpage即可

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// 用户认证信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	// 设置用户账号信息和权限
	 auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("showOrder","addOrder","updateOrder","deleteOrder");
	 // 添加 useradd账号 只有添加查询和添加订单权限
	 auth.inMemoryAuthentication().withUser("userAdd").password("123456")
		.authorities("showOrder","addOrder");
}

// 配置HttpSecurity 拦截资源
protected void configure(HttpSecurity http) throws Exception {

// // 拦截请求, 权限名称
http.authorizeRequests()
.antMatchers("/showOrder").hasAnyAuthority(“showOrder”)
.antMatchers("/addOrder").hasAnyAuthority(“addOrder”)
.antMatchers("/login").permitAll()
.antMatchers("/updateOrder").hasAnyAuthority(“updateOrder”)
.antMatchers("/deleteOrder").hasAnyAuthority(“deleteOrder”)
//并且关闭csrf
.antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();

}

// SpringBoot2.0抛弃了原来的NoOpPasswordEncoder,要求用户保存的密码必须要使用加密算法后存储,在登录验证的时候Security会将获得的密码在进行编码后再和数据库中加密后的密码进行对比
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
	return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}

}

<#if RequestParameters[‘error’]??>
用户名称或者密码错误
</#if>

认证成功或者失败处理

AuthenticationFailureHandler 认证失败接口
AuthenticationSuccessHandler 认证成功接口

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
		throws IOException, ServletException {
	System.out.println("用户认证失败");
	res.sendRedirect("http://www.mayikt.com");
}

}

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

// 用户认证成功
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth)
		throws IOException, ServletException {
	System.out.println("用户登陆成功");
	res.sendRedirect("/");
}

}

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationSuccessHandler successHandler;
@Autowired
private MyAuthenticationFailureHandler failHandler;
// 用户认证信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 设置用户账号信息和权限
auth.inMemoryAuthentication().withUser(“admin”).password(“123456”).authorities(“showOrder”,“addOrder”,“updateOrder”,“deleteOrder”);
// 添加 useradd账号 只有添加查询和添加订单权限
auth.inMemoryAuthentication().withUser(“userAdd”).password(“123456”)
.authorities(“showOrder”,“addOrder”);
}

// 配置HttpSecurity 拦截资源
protected void configure(HttpSecurity http) throws Exception {

// // 拦截请求, 权限名称
http.authorizeRequests()
.antMatchers("/showOrder").hasAnyAuthority(“showOrder”)
.antMatchers("/addOrder").hasAnyAuthority(“addOrder”)
.antMatchers("/login").permitAll()
.antMatchers("/updateOrder").hasAnyAuthority(“updateOrder”)
.antMatchers("/deleteOrder").hasAnyAuthority(“deleteOrder”)
//并且关闭csrf
.antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").successHandler(successHandler).failureHandler(failHandler).and().csrf().disable();

}

// SpringBoot2.0抛弃了原来的NoOpPasswordEncoder,要求用户保存的密码必须要使用加密算法后存储,在登录验证的时候Security会将获得的密码在进行编码后再和数据库中加密后的密码进行对比
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
	return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}

}

Spring Boot整合Spring Security主要是为了提供安全控制功能,帮助开发者快速地在Spring Boot应用中添加身份验证、授权和会话管理等安全性措施。以下是基本步骤: 1. 添加依赖:首先,在Maven或Gradle项目中添加Spring Security的相关依赖到pom.xml或build.gradle文件中。 ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Gradle --> implementation 'org.springframework.boot:spring-boot-starter-security' ``` 2. 配置WebSecurityConfigurerAdapter:在`src/main/resources/application.properties`或application.yml中配置一些基础属性,如启用HTTPS、密码加密策略等。然后创建一个实现了`WebSecurityConfigurerAdapter`的类,进行具体的配置,如设置登录页面、认证器、过滤器等。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**", "/js/**", "/images/**").permitAll() // 允许静态资源访问 .anyRequest().authenticated() // 所有其他请求需要认证 .and() .formLogin() // 设置基于表单的身份验证 .loginPage("/login") // 登录页URL .defaultSuccessUrl("/") // 登录成功后的默认跳转URL .usernameParameter("username") .passwordParameter("password") .and() .logout() // 注销功能 .logoutUrl("/logout") .logoutSuccessUrl("/") .deleteCookies("JSESSIONID"); } // ... 其他配置如自定义用户DetailsService、密码编码器等 } ``` 3. 用户服务(UserDetailsService):如果需要从数据库或其他数据源获取用户信息,需要实现`UserDetailsService`接口并提供用户查询逻辑。 4. 运行应用:启动Spring Boot应用后,Spring Security将自动处理HTTP请求的安全检查,例如身份验证和授权。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值