前言

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运算

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

springSecurity实现简单的登录功能的更多相关文章

  1. PHP+jquery+CSS制作头像登录窗(仿QQ登陆)

    本篇文章介绍了PHP结合jQ和CSS制作头像登录窗(仿QQ登陆),实现了类似QQ的登陆界面,很有参考价值,有需要的朋友可以了解一下。

  2. NodeJS实现单点登录原理解析

    随着公司业务的增多,必然会产生各个不同的系统,如果每个系统都需要单独登录的话就会很不方便,所以这个时候单点登录会很方便,今天通过本文给大家讲解NodeJS实现单点登录原理解析,感兴趣的朋友一起看看吧

  3. springSecurity实现简单的登录功能

    这篇文章主要为大家详细介绍了springSecurity实现简单的登录功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  4. java web实现简单登录注册功能全过程(eclipse,mysql)

    前期我们学习了javaweb项目用JDBC连接数据库,还有数据库的建表功能,下面这篇文章主要给大家介绍了关于java web实现简单登录注册功能的相关资料,需要的朋友可以参考下

  5. php注册登录系统简化版

    这篇文章主要为大家详细介绍了php注册登录系统简化版的实现步骤,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  6. 微信小程序实现手机验证码登录

    这篇文章主要为大家详细介绍了微信小程序实现手机验证码登录,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  7. TP5框架简单登录功能实现方法示例

    这篇文章主要介绍了TP5框架简单登录功能实现方法,结合实例形式分析了thinkPHP5框架登录功能控制器、视图、登录验证等相关操作技巧,需要的朋友可以参考下

  8. HTML+jQuery实现简单的登录页面

    这篇文章主要介绍了用三种方法实现简单的登录页面的制作:纯HTML、HTML+jQuery(form data)格式、HTML+jQuery(json)格式。感兴趣的同学可以跟随小编一起学习一下

  9. android实现简易登录注册界面及逻辑设计

    这篇文章主要为大家详细介绍了android实现简易登录注册界面及逻辑设计,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android Studio实现注册页面跳转登录页面的创建

    这篇文章主要为大家详细介绍了Android Studio实现注册页面跳转登录页面的创建,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

随机推荐

  1. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  3. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  4. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  5. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  6. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  7. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  8. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  9. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Spring JdbcTemplate执行数据库操作详解

    JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作更加方便、友好,效率也不错,这篇文章主要介绍了Spring JdbcTemplate执行数据库操作,需要的朋友可以参考下

返回
顶部