一、权限管理的概念

另一个安全框架shiro:shiro之权限管理的描述


导入常用坐标

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

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.3.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <version>2.3.9.RELEASE</version>
    </dependency>

二、spring security用户认证

1.用户认证之application.properties配置文件

spring.security.user.name=admin
spring.security.user.password=admin

2.用户认证之自定义配置文件

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode("admin");
        auth.inMemoryAuthentication().withUser("admin").password(encode).roles();
    }
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

3.数据库查询(这一种也是最常用的)

1.使用mybatis plus框架处理dao层

      <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

2.创建数据库表
在这里插入图片描述

3.编写mapper文件

@Repository
public interface UserMapper extends BaseMapper<Users> {

}

4.编写service

package com.zsh.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsh.security.mapper.UserMapper;
import com.zsh.security.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;

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2021/3/12
 * @description:
 */
@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", s);
        Users users = userMapper.selectOne(wrapper);
        if (users == null) {
            throw new UsernameNotFoundException("账号或密码错误!");
        } else {
            List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
            return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
        }

    }
}

5.编写配置文件

package com.zsh.security.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;

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2021/3/12
 * @description:
 */
@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

6.配置数据库连接

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springsecurity?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin

7.运行
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

过滤器链


三、自定义登录界面

1.在SecurityConfig2中加入有关http的实现方法

package com.zsh.security.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;

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2021/3/12
 * @description:
 */
@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html")   //设置登录界面
                .loginProcessingUrl("/user/login")  //登录界面url
                .defaultSuccessUrl("/test/index").permitAll()     //默认登录成功界面
                .and().authorizeRequests()      //哪些资源可以直接访问
                    .antMatchers("/","/test/hello","/user/loin").permitAll()    //不做处理
                .anyRequest().authenticated()   //所有请求都可以访问
                .and().csrf().disable();        //关闭CSRF
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}

2.login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body> <!--name必须是username和password -->
    <form action="/user/login" method="post">
        username:<input type="text" name="username"> <br>
        password:<input type="password" name="password"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

3.controller

@RestController
@RequestMapping("/test")
public class SecurityController {

    @RequestMapping("/hello")
    public String hello() {

        return "hello! Spring Security!";
    }

    @RequestMapping("/index")
    public String index() {
        return "hello index!";
    }
}

4.访问http://localhost:8080/test/hello
在这里插入图片描述
5.访问http://localhost:8080/login.html
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

posted on 2021-03-13 09:12  凸凸大军的一员  阅读(531)  评论(0编辑  收藏  举报