springSecurity实现简单的登录功能

 更新时间:2022年09月06日 14:58:33   作者:_Kc  
这篇文章主要为大家详细介绍了springSecurity实现简单的登录功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

前言

1、不使用数据库,实现一个简单的登录功能,只有在登录后才能访问我们的接口
2、springSecurity提供了一种基于内存的验证方法(使用自己定义的用户,不使用默认的)

一、实现用户创建,登陆后才能访问接口(注重用户认证)

1.定义一个内存用户,不使用默认用户

重写configure(AuthenticationManagerBuilder auth)方法,实现在内存中定义一个 (用户名/密码/权限:admin/123456/admin) 的用户

package com.example.springsecurity;

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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存的验证方法
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {             //批处理静态资源,都不拦截处理
        web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

2.效果

根目录可以直接通过验证,其他接口需要经过springSecurity,输入admin 123456后登陆系统

3.退出登陆

地址栏输入:http://localhost:8080/login?logout,执行退出登陆

4.再创建一个张三用户,同时支持多用户登陆

package com.example.springsecurity;

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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存的验证方法
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {             //批处理静态资源,都不拦截处理
        web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

二、实现管理员功能(注重权限控制)

实现角色功能,不同角色拥有不同功能:管理员拥有管理功能,而普通组员只能拥有最普通的功能

1.创建一个普通用户demo

auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");

创建demo用户,角色为demo,详细代码如下

package com.example.springsecurity;

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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存的验证方法
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {             //批处理静态资源,都不拦截处理
        web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

2.创建/roleAuth接口

此接口只能admin角色才能登陆

1)、@EnableGlobalMethodSecurity注解使role验证注解生效
2)、@PreAuthorize(“hasRole(‘ROLE_admin’)”)注解声明哪个角色能访问此接口

package com.example.springsecurity;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)  //必须加这行,不然role验证无效
public class SpringsecurityApplication {

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

    @RequestMapping("/")
    public String home(){
        return "hello spring boot";
    }

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

    @PreAuthorize("hasRole('ROLE_admin')")  //当我们期望这个方法经过role验证的时候,需要加这个注解;ROLE必须大写
    @RequestMapping("/roleAuth")
    public String role(){
        return "admin  Auth";
    }

}

3.效果

demo用户登陆成功可以访问/接口,但是不能访问/roleAuth接口

admin管理员既能访问/接口,也能访问/roleAuth接口

三、实现数据库管理用户(注重数据库认证用户)

1.我们需要把之前创建的admin zhangsan demo三个用户放到数据库中 2.我们需要使用MyUserService来管理这些用户
1.创建一个MyUserService类
1.此类实现UserDetailsService(这边不真实查询数据库)

package com.example.springsecurity;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class MyUserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return null;//数据库操作逻辑
    }
}

2.密码自定义验证类
1.此类实现自定义密码验证

package com.example.springsecurity;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswdEncoder implements PasswordEncoder {
    private final static String SALT = "123456";
    @Override
    public String encode(CharSequence rawPassword) {
        //加密:堆原始的密码进行加密,这边使用md5进行加密
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        return encoder.encodePassword(rawPassword.toString(), SALT);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        //拿原始的密码和加密后的密码进行匹配
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        return encoder.isPasswordValid(encodedPassword,rawPassword.toString(),SALT);
    }
}

3.自定义数据库查询&默认数据库查询、自定义密码验证配置
1.支持自定义数据库查询 2.支持默认数据库查询(数据库结构必须和默认的一致) 两者选择其中一个

package com.example.springsecurity;

import org.springframework.beans.factory.annotation.Autowired;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyUserService myUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基于内存的验证方法
//        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
//        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
//        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");


        //1、自己实现数据库的查询,指定我们要使用的UserService和自定义的密码验证器
        auth.userDetailsService(myUserService).passwordEncoder(new MyPasswdEncoder());
        //2、sprinSecurity在数据库管理方面支持一套默认的处理,可以指定根据用户查询,权限查询,这情况下用户表必须和默认的表结构相同,具体查看user.ddl文件

        auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswdEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {             //批处理静态资源,都不拦截处理
        web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {       // 这是一个重要的方法,这个方法决定了我们哪些请求会被拦截以及一些请求该怎么处理
        http.authorizeRequests()  //安全过滤策略
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and() //and添加允许别的操作
                .logout().permitAll() //允许支持注销,支持随意访问
                .and()
                .formLogin();   //允许表单登录
        http.csrf().disable();  //关闭csrf认证
    }
}

四、sprinSecurity支持的4种使用表达式的权限注解

1.支持的4种注解

@PreAuthorize("hasRole('ROLE_admin')")  //1.方法调用前:当我们期望这个方法经过role验证的时候,需要加这个注解;ROLE必须大写
    @PostAuthorize("hasRole('ROLE_admin')")//2.方法调用后
    @PreFilter("")//2.对集合类的参数或返回值进行过滤
    @PostFilter("")//2.对集合类的参数或返回值进行过滤
    @RequestMapping("/roleAuth")
    public String role(){
        return "admin  Auth";
    }

2.注解的参数该怎么传

or用法:

参数的值判断

and运算

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 软件开发基础之设计模式概述

    软件开发基础之设计模式概述

    这篇文章介绍了软件开发基础之设计模式,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-09-09
  • java采用中文方式显示时间的方法

    java采用中文方式显示时间的方法

    这篇文章主要介绍了java采用中文方式显示时间的方法,实例分析了java时间操作及字符串转换的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • Pulsar源码彻底解决重复消费问题

    Pulsar源码彻底解决重复消费问题

    这篇文章主要为大家介绍了Pulsar源码彻底解决重复消费问题,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • Java日志logback的使用配置和logback.xml解读

    Java日志logback的使用配置和logback.xml解读

    这篇文章主要介绍了Java日志logback的使用配置和logback.xml解读,具有很好的价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • Java实现象棋算法的示例代码

    Java实现象棋算法的示例代码

    象棋算法包括搜索算法、评估函数和剪枝算法,本文主要介绍了Java实现象棋算法的示例代码,具有一定的参考价值,感兴趣的可以了解一下
    2023-12-12
  • SpringBoot整合SpringSecurity实现JWT认证的项目实践

    SpringBoot整合SpringSecurity实现JWT认证的项目实践

    本文会通过创建SpringBoot项目整合SpringSecurity,实现完整的JWT认证机制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • java+vue实现添加单选题、多选题到题库功能

    java+vue实现添加单选题、多选题到题库功能

    这篇文章主要为大家详细介绍了java+vue实现添加单选题、多选题到题库功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-04-04
  • 如何理解Java中基类子对象的构建过程从

    如何理解Java中基类子对象的构建过程从"基类向外"进行扩散的?

    今天小编就为大家分享一篇关于如何理解Java中基类子对象的构建过程从"基类向外"进行扩散的?,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04
  • Java毕业设计实战之在线高中考试系统的实现

    Java毕业设计实战之在线高中考试系统的实现

    这是一个使用了java+SSM+Jsp+Mysql+Maven开发的在线高中考试系统,是一个毕业设计的实战练习,具有考试系统该有的所有功能,感兴趣的朋友快来看看吧
    2022-02-02
  • Spring如何基于注解显式实现自动装配

    Spring如何基于注解显式实现自动装配

    这篇文章主要介绍了Spring如何基于注解显式实现自动装配,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08

最新评论