欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Security中的用户注销

程序员文章站 2024-03-19 15:41:52
...

实现过程:
登录成功后进入一个页面,点击退出后,无法访问需要权限的页面。

pom.xml

<?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.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.rixin</groupId>
    <artifactId>springsecuritydemo2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springsecuritydemo2</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-web</artifactId>
        </dependency>

        <!--spring security依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

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

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

</project>

application.properties

server.port=8112

# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springsecuritydemo?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=1234

login.html

<!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"/>
        password:<input type="password" name="password"/>
        <input type="submit" value="login"/>
    </form>
</body>
</html>

success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/logout">退出</a>
</body>
</html>

unauth.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>没有访问权限</h1>
</body>
</html>

Springsecuritydemo2Application.java

package com.rixin.springsecuritydemo2;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

@MapperScan("com.rixin.springsecuritydemo2.mapper")
@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled = true)
@SpringBootApplication
public class Springsecuritydemo2Application {

    public static void main(String[] args) {
        SpringApplication.run(Springsecuritydemo2Application.class, args);
    }

}

User.java

package com.rixin.springsecuritydemo2.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class User {

    private Integer id;
    private String username;
    private String password;

}

UserMapper.java

package com.rixin.springsecuritydemo2.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rixin.springsecuritydemo2.entity.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper<User> {
}

MyUserDetailsService.java

package com.rixin.springsecuritydemo2.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rixin.springsecuritydemo2.mapper.UserMapper;
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("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    //s是表单传入的用户名
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //查询数据库
        QueryWrapper<com.rixin.springsecuritydemo2.entity.User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        com.rixin.springsecuritydemo2.entity.User user = userMapper.selectOne(wrapper);
        //判断
        if (user == null) {
            //认证失败
            throw new UsernameNotFoundException("用户名不存在!");
        }
        //授予用户权限
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_sale");
        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}

SecurityConfig.java

package com.rixin.springsecuritydemo2.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 SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

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

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

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

        //退出
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();

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


        //自定义用户登录页面
        http.formLogin()
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login") //登录访问路径
                .defaultSuccessUrl("/success.html").permitAll() //登录成功后的跳转路径
                .and().authorizeRequests() //定义哪些url被保护,哪些不被保护
                    .antMatchers("/","/test/hello","/user/login").permitAll() //访问这些路径不需要认证
                    //.antMatchers("/test/index").hasAuthority("admins") //当前登录用户,只有具有admins权限才可以访问这个路径
                    //.antMatchers("/test/index").hasAnyAuthority("admins,manager")
                    //.antMatchers("/test/hello").hasRole("sale")
                    .antMatchers("/test/hello").hasAnyRole("sale")
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护

    }
}

TestController.java

package com.rixin.springsecuritydemo2.controller;

import com.rixin.springsecuritydemo2.entity.User;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

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

    @GetMapping("hello")
    public String add() {
        return "hello security";
    }

    @GetMapping("index")
    public String index() {
        return "hello index";
    }

    @GetMapping("update")
    //@Secured({"ROLE_sale","ROLE_manager"})
    @PreAuthorize("hasAnyAuthority('manager')")
    public String update() {
        return "hello update";
    }

    @GetMapping("getAll")
    @PreAuthorize("hasAnyAuthority('manager')")
    @PostFilter("filterObject.username == '44'")
    public List<User> getAllUser() {
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(1,"22","33"));
        list.add(new User(2,"44","33"));
        return list;
    }

}