Spring Security 学习笔记

目录

一、基本原理

二、两个重要接口

三、web权限认证方式

3.1设置登录的用户名和密码

四、查询数据库完成用户认证

五、自定义登录页面

六、基于角色权限访问控制

1.hasAuthority 方法(针对一个权限)        

2.hasAnyAuthority方法(针对多个权限)

3.hasRole

 4.hasAnyRole​

 七、自定义403没有权限访问的页面

八、认证授权注解使用

九、用户注销  

十、自动登录


一、基本原理

二、两个重要接口

三、web权限认证方式

3.1设置登录的用户名和密码

3.1.1 第一种方式:通过配置文件

        

3.1.2 第二种方式:通过配置类

        1.新建SecurityConfig 配置类,继承  WebSecurityConfigurerAdapter 

        2.重写  configure(AuthenticationManagerBuilder auth)方法

        

package com.cn.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // 引入 BCryptPasswordEncoder 对象
        String password = passwordEncoder.encode("123456"); // 对密码进行加密
        //设置username 和 password , role
        auth.inMemoryAuthentication().withUser("lucky").password(password).roles("admin");



    }
@Bean
    PasswordEncoder password(){

        return new BCryptPasswordEncoder();
    }

}

        

3.1.3 第三种方式:自定义编写实现类

        1. 创建配置类,设置使用哪个userDetailService实现类;

package com.cn.config;

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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(password());

    }

    @Bean
    PasswordEncoder password(){

        return new BCryptPasswordEncoder();
    }

}

        2.编写实现类,返回user对象,User对象有用户名和密码和操作权限;

package com.cn.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailService")
public class MyUserDetailServiceImpl implements UserDetailsService {


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //权限集合
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");

        //返回user 对象
        return new User("mary",new BCryptPasswordEncoder().encode("123456"),auths);
    }
}

四、查询数据库完成用户认证

1.整合Mybatis-Plus;

2.引入依赖;

3.创建user实体类;

4. 创建UserMapper 接口 继承 BaseMapper<User> ;

5. 在UserDetailService 调用mapper 里面的方法查询数据库;

package com.cn.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.mapper.UserMapper;
import com.cn.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailService")
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //调用userMapper,根据用户名 方法查询数据库
        QueryWrapper<Users> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        Users user  = userMapper.selectOne(queryWrapper);
        //判断
        if(user == null ){
            throw new UsernameNotFoundException("数据库没找到用户名");
        }


        //权限集合
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");

        //返回user 对象
        return new User(username,new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}

6.在启动类加上注解@MapperScan("com.cn.mapper");

五、自定义登录页面

1.在配置类中重新方法 configure(HttpSecurity http)

package com.cn.config;

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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(password());

    }

    @Bean
    PasswordEncoder password(){

        return new BCryptPasswordEncoder();
    }

    // 自定义登录页面配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin() //自定义自己编写的登录页面
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login") //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll() //登录成功后,跳转路径
                .and().authorizeRequests()
                // 设置哪些路径可以直接访问,不需要认证
                .antMatchers("/","/test/hello","user/login").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护
    }
}

2. 创建 html 页面

在resource 目录下创建static文件夹 ,创建login.html登录页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/user/login" method="post">
    <!-- 这个必须叫username和password,否则会报错 -->
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
</form>
</body>
</html>

action访问路径要与配置文件中访问路径一致

六、基于角色权限访问控制

1.hasAuthority 方法(针对一个权限)        

        1.在配置类设置当前访问路径,哪些权限可以访问

         2.在UserDetailService,把返回User对象设置权限

 3.测试,没有访问权限 403

2.hasAnyAuthority方法(针对多个权限)

3.hasRole

 

 4.hasAnyRole

 

 七、自定义403没有权限访问的页面

1.在配置类设置自定义页面

package com.cn.config;

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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(password());

    }

    @Bean
    PasswordEncoder password(){

        return new BCryptPasswordEncoder();
    }

    // 自定义登录页面配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //配置没有权限访问跳转自定义页面
        http.exceptionHandling().accessDeniedPage("/unauth.html");

        http.formLogin() //自定义自己编写的登录页面
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login") //登录访问路径
                .defaultSuccessUrl("/test/index").permitAll() //登录成功后,跳转路径
                .and().authorizeRequests()
                // 设置哪些路径可以直接访问,不需要认证
                .antMatchers("/","/test/hello","user/login").permitAll()


                //1.hasAuthority当前登录的用户,只有具有admin权限才可以访问
                //.antMatchers("/test/index").hasAuthority("admins")

                //当前用户具有多个权限
                //2.hasAnyAuthority
                //.antMatchers("/test/index").hasAnyAuthority("ROLE_admins","manager")

                //3.hasRole
                //.antMatchers("/test/index").hasRole("sale")

                //4.hasAnyRole
                .antMatchers("/test/index").hasAnyRole("sale")
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护
    }
}

八、认证授权注解使用

8.1.@Secured 用户具有某个角色,可以访问方法

        1.在启动类或者配置类上开启注解    @EnableGlobalMethodSecurity(securedEnabled = true)

        2.在controller 的方法上面使用注解,设置角色

             

        3.  在userDetailService 实现类中设置用户角色

        

 8.2 @PreAuthorize 适合进入方法前的权限验证,可以将登录用户的roles/permissions 传参到方法中

        1.在启动类中开启注解  

         @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)          

         2.在controller的方法上面添加注解

        

8.3 @PostAuthorize 在方法执行之后进行校验

         

        1.在启动类中开启注解  

         @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)       

         2.在controller的方法上面添加注解

        

8.4 @PostFilter   方法返回的数据进行过滤

8.5 @PreFilter   传入方法数据进行过滤

九、用户注销  

在配置类中添加一个退出路径

十、自动登录

 

         1.   创建数据库表

       

"create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, token varchar(64) not null, last_used timestamp not null);

        2.配置类,注入数据库,配置操作数据库对象

         3.配置类配置自动登录

         4.在登录页面添加复选框(名字必须叫 remember-me)

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值