SpringSecurity基础知识

SpringSecurity

1.Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。
2.SpringSecurity核心功能:认证(身份校验,你是谁),授权(你能干什么),攻击防护(防止伪造身份

在这里插入图片描述

Spring security自定义实现

springsecurity无自定义时默认一个user用户和随机密码
方法:
第一种:通过配置文件定义用户和密码spring.security.user.name/password=xxx.
第二种:通过配置类实现(继承WebSecurityConfigurerAdapter并重写configure方法)
通过自定义配置类(实现UserDatailsService接口)<即数据库查询的真实数据>

自定义用户认证服务

2.1基于WebSecurityConfigureAdapter实现数据库的查询

2.2.2:数据库定义t_role角色表,t_user用户表和t_user_role用户角色表.

在这里插入图片描述

在这里插入图片描述

2.2.3导入相关的依赖和mysql基本信息.
2.2.4

package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private DataSource dataSource;
    //用户查询密码
    String pwdQuery="select user_name,pwd,available from t_user where user_name=?";
    String roleQuery="select u.user_name,r.role_name from t_user u,t_user_role ur,t_role r\n" +
            "            where u.id=ur.user_id and r.id=ur.role_id\n" +
            "            and u.user_name=?";
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(10);
        //Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(this.secret);
        auth.jdbcAuthentication()
                //.passwordEncoder(NoOpPasswordEncoder.getInstance())
                .passwordEncoder(bCryptPasswordEncoder)
                .dataSource(dataSource)
                .usersByUsernameQuery(pwdQuery)
                .authoritiesByUsernameQuery(roleQuery);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();

    }
}

1.关于数据库存储密码加密的问题,可以百度找Bcypt进行加密复制来进行测试.

2.如果数据库存储的是明文的形式会出现Encoded password does not look like BCrypt 异常问题,也可以通过spring废弃的NoOpPasswordEncoder.getInstance()指定不进行数据密码加密

请添加图片描述

2.2.4数据库密码加密信息
请添加图片描述

2.2.5进行登录测试
请添加图片描述

2.2.6测试成功请添加图片描述

2.SpringSecurity限制请求

对于一个网站可以拥有不同的角色则各自的权限也不相同,例如普通用户和VIP
1.可以通过WebSecurityConfigureAdapter的重写configure(HttpSecurity)方法对请求进行限制

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                //允许角色user,admin访问指定路径/user/welcome or /details
            .antMatchers("/user/welcome","/user/details").hasAnyRole("USER","ADMIN")
                //只允许admin角色访问admin/**路径
            .antMatchers("/admin/**").hasAnyAuthority("ROLE_ADMIN")
                .anyRequest().permitAll()
                .and()
                .anonymous()
                .and().formLogin().and().httpBasic();
    }
    
2.也可以通过注解@PreAuthorize(value="xxx")在请求路径指定可以访问的用户权限,<2个实现方法一样,按需选择>

@RestController
public class HekController {

    @PreAuthorize(value = "hasAnyRole('ADMIN','USER')")
    @RequestMapping("/user/welcome")
    public String getwelcome(){

        return "welcome SpringSecurity";
    }
    @PreAuthorize(value = "hasAnyRole('ADMIN','USER')")
    @RequestMapping("/user/details")
    public String getdetails(){

        return "Hello SpringSecurity";
    }
    @PreAuthorize(value = "hasAuthority('ROLE_ADMIN')")
    @RequestMapping("/admin/details")
    public String getadmin(){

        return "只有admin权限才能访问此页面";
    }
}

3.对于没有权限而去访问的用户,则出现(type=Forbidden, status=403)不允许访问
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值