SpringBoot整合安全性框架SpringSecurity

SpringSecurity是一种基于Spring应用提供的声明式的安全保护性的框架,它可以在web请求级别的和方法调用级别处理身份和授权。

首先需要在Maven中导包:

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

因为SpringSecurity是基于Spring的安全性框架,所以可以完美契合SpringBoot,导完包就可以直接使用了,与SpringBoot扩展配置MVC一样,也需要先建一个SecurityConfig配置类。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {}

这个SecurityConfig配置类需要继承WebSecurityConfigurerAdapter。然后配置注解@EnableWebSecurity将其由Spring托管。

然后就是简单的用户认证和授权功能,只需要重写两个方法。

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**授权:*/
        /*首页所有人可以访问,功能页只有对应有权限(vip)的人才能访问*/
        http.authorizeRequests().antMatchers("/index").permitAll()
                .antMatchers("/Dashboard/**").hasRole("vip");
        
        /*没有权限进入登录界面  默认跳转地址:/login Security默认页面*/
        http.formLogin()
        		.loginPage("无权限跳转的页面地址");

        /*注销登录  :/logout   删除cookie*/
        http.logout()
                .logoutUrl("自定义登出页面的地址")
                /*要删除的cookie 的key*/
    			.deleteCookies("JSESSIONID")
    			/*清空session*/
    			.invalidateHttpSession(true)}

然后就是用户认证,给符合条件的对应用户添加权限。

	@Autowired
    private LoginMapper loginMapper;
/**用户认证,并对用户密码进行加密--BCryptPasswordEncoder*/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        for (int i = 0; i < loginMapper.queryUser().size();i++){
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser(loginMapper.queryUser().get(i).getUsername())
                    .password(new BCryptPasswordEncoder().encode(loginMapper.queryUser().get(i).getPassword()))
                    .roles("vip");
        }
    }

这里我用的是从内存读取数据,inMemoryAuthentication(),当然也可以选择连接数据库从数据库中直接读取,那么只要使用jdbcAuthentication()以及对应方法即可。还要装配数据源的bean。

	@Autowired
    private DataSource dataSource;

这里为了数据安全,还要对用户密码进行加密,使用.passwordEncoder(new BCryptPasswordEncoder())方法new BCryptPasswordEncoder().encode()即可将用户密码进行密文传递,保证安全性。

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Security是Spring家族中非常重要的安全框架,可以提供登录认证、授权、攻击防护等安全性功能。而Spring Boot是简化了Spring应用的开发,使得开发人员可以快速创建基于Spring的应用程序。 Spring Boot与Spring Security的整合非常简单,只需要在项目中添加Spring Security的依赖即可。下面是一个简单的Spring Boot整合Spring Security的示例。 1.添加依赖 在pom.xml文件中添加Spring Security的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2.配置Security 在项目中添加一个Security配置类,该类需要继承WebSecurityConfigurerAdapter类,并重写configure()方法,用于配置Spring Security的相关设置。 ``` @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/home").permitAll() .antMatchers("/admin/**").access("hasRole('ADMIN')") .and().formLogin() .and().exceptionHandling().accessDeniedPage("/accessDenied"); } } ``` 在上面的配置中,我们定义了一个内存中的用户,用户名为"user",密码为"password",角色为"USER"。同时,我们还配置了请求路由的访问规则,根路径和"/home"路径都是允许所有人访问的,而以"/admin/"开头的路径则需要具备"ADMIN"角色才能访问。最后,我们还为访问被拒绝的用户定义了一个跳转页面。 3.启动应用程序 在完成上述配置之后,我们只需要启动Spring Boot应用程序即可。在浏览器中输入http://localhost:8080/,会看到一个默认的Spring Security登录页面,输入我们在配置中定义的用户名和密码即可登录成功。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yui方木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值