一、导入坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zsh</groupId>
    <artifactId>springsecurity</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springsecurity</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、Users实体类及其数据库表的创建

@Data
public class Users {

    private int id;
    private String username;
    private String password;
}

在这里插入图片描述

#spring.security.user.name=admin
#spring.security.user.password=admin
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=hao20001010

三、controller,service,mapper层的实现

@RestController
@RequestMapping("/test")
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityController {

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

        return "hello! Spring Security!";
    }

    @PreAuthorize("hasRole('admin')")
    @RequestMapping("/index")
    public String index() {
        return "hello index!";
    }

    @GetMapping("/delete")
    @Secured({"ROLE_user","ROLE_admin"})
    public String delete() {
        return "delete merchandise";
    }

    @GetMapping("/add")
    @PreAuthorize("hasAuthority('admin')")
    public String add() {
        return "add";
    }

    @GetMapping("/update")
    @PostAuthorize("hasAnyAuthority('user')")
    public String update() {
        System.out.println("update方法已经执行!");
        return "update";
    }


}
@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_admin");
            return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
        }

    }
}

@Repository
public interface UserMapper extends BaseMapper<Users> {

}

四、核心–编写配置文件

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 {
        //logout实现注销,注销之后跳转到fail.html
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/fail.html").permitAll();
        http.exceptionHandling().accessDeniedPage("/noauth.html");
        http.formLogin()
                .loginPage("/login.html")   //设置登录界面
                .loginProcessingUrl("/user/login")  //登录界面url
                .defaultSuccessUrl("/success.html").permitAll()     //默认登录成功界面
                .and().authorizeRequests()      //哪些资源可以直接访问
                    .antMatchers("/","/test/hello","/user/loin").permitAll()    //不做处理
                    //.antMatchers("/test/index").hasAuthority("admin")
//                    .antMatchers("/test/index").hasAnyAuthority("admin","manager")
                    //.antMatchers("/test/index").hasRole("admin")
                      .antMatchers("/test/index").hasRole("admin")
                .anyRequest().authenticated()   //所有请求都可以访问
                .and().csrf().disable();        //关闭CSRF
    }

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


}

五、页面的实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <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>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a>已退出!</a>
    <a href="/login.html">去登陆</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a style="background-color: red; margin-top: 100px; margin-left: 100px">no auth</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a>登录成功</a>
    <a href="/logout">注销登录</a>
</body>
</html>

运行结果

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述
当在登录状态时,直接去访问/test/index 能够直接到主页面

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