申明
文章只是简单的介绍在springboot中的使用,如果想看springsecurity原理,可以转向下面这篇文章:
Spring Security 工作原理概览
别模仿博客内容
Security的授权认证
1、导入Spring Security的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
2、编写Security的配置类
package com.jet5devil.srpingbootdata.config;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/view1/**").hasRole("vip1")
.antMatchers("/view2/**").hasRole("vip2")
.antMatchers("/view3/**").hasRole("vip3");
// 定制登录页
// 前后端交互的时候,前端name可能和后端security设置的默认值不同,需要使用usernameParameter来匹配
// loginProcessingUrl 处理地址,loginPage请求地址
http.formLogin().loginPage("/login1").usernameParameter("title").passwordParameter("password").loginProcessingUrl("/login");
http.logout().logoutSuccessUrl("/");
http.csrf().disable(); // 关闭csrf,登录失败存在的原因
// 记住我
http.rememberMe().rememberMeParameter("rememberMe");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuang").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1", "vip2")
.and()
.withUser("jet").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1", "vip2", "vip3");
}
}
类需要继承WebSecurityConfigurerAdapter
,里面有许多的重载的configure方法,有的是关于授权的有的是关于认证的,代码中的第一个configure,…